File

advertisement
#Functions Lecture Notes
base = 10
exp = 4
def hello_world():
base = 20
print "inside of helloworld base is", base
# Display the string "Hello, world!"
return "Hello, world!"
print hello_world()
print "outside of helloworld base is", base
def ret_5():
print 5
# What is returned here?
print ret_5()
def compute_exp(base, exp):
#Computes a base raised to the power of exp
#base must be a float or int
#exp must be a float or int
print "inside of function, base is", base
print "inside of function, exp is:", exp
return base**exp
print "outside of function, base is", base
print "outside of function, exp is:", exp
# Test cases
print compute_exp(5, 0)
print compute_exp(5, 3)
print compute_exp(8, 2)
# def starts a function definition
# names of functions follow variable naming conventions
# functions can take zero or more parameters
def is_a_party(apples, pizzas):
# Returns True if you have enough apples and pizzas to make a
party happen
if apples > 10 and pizzas > 10:
return True
else:
return False
# A function with zero parameters
def throw_party():
num_apples = input("How many apples do you have? ")
num_pizzas = input("How many pizzas do you have? ")
# Ask if this is enough for a party
if is_a_party(num_apples, num_pizzas):
return "Dude let's party down"
else:
return "You'll have to go to the store first."
## Testing the functions
print is_a_party(20, 20)
print is_a_party(5, 15)
print is_a_party(5, 2)
print is_a_party(14, 8)
print throw_party()
#Check_for_vowels
def is_a_vowel(c):
# check if c is a vowel
if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u':
# Return True if c is a vowel
return True
elif c == 'A' or c == 'E' or c == 'I' or c == 'O' or c == 'U':
# Also return True if c is a capital vowel
return True
else:
# c must not be a vowel; return False
return False
## Testing
print is_a_vowel("u")
print is_a_vowel("E")
print is_a_vowel("x")
def only_vowels(phrase):
# Takes a phrase, and returns a string of all the vowels
# Initalize an empty string to hold all of the vowels
vowel_string = ''
for letter in phrase:
# check if each letter is a vowel
if is_a_vowel(letter):
# If it's a vowel, we append the letter to the vowel
string
vowel_string = vowel_string + letter
# if not a vowel, we don't care about it- so do nothing!
return vowel_string
# Code after a "return" doesn't print
print "A line of code after the return!"
# Testing the functions
print "The vowels in the phrase 'tim the beAver' are:",
only_vowels("tim the beAver")
print only_vowels("HeLlO wOrLd!!")
print only_vowels("klxn") # Expect no vowels from this one!
Download