The term "fruitful" refers to the fact that the function called will return something (bear fruit) to whoever called it.
Since the first week of class we have been using functions, such as type(5)
,
print("hello")
, and int(raw_input("age? "))
. In week 4 we learned about
arguments, parameters, return values, and how to write simple functions.
Hopefully by now you are comfortable with function basics.
This week we will look at all the details of writing and using functions.
After fall break we will start writing programs with many functions, focussing
on how to design larger, more complex programs.
Take a look at the following program and see if you can figure out what it will do and what it will print to the screen.
def main():
S = "we love comp sci!"
L = list(S)
numVowels = capitalizeVowels(L)
newS = "".join(L)
print(numVowels)
print(newS)
def capitalizeVowels(mylist):
"""count and capitalize the vowels"""
count = 0
for i in range(len(mylist)):
if isVowel(mylist[i]):
mylist[i] = mylist[i].upper()
count += 1
return count
def isVowel(ch):
"""return True if ch is a vowel, False if not"""
vowels = "aeiou"
if ch.lower() in vowels:
return True
else:
return False
main()
After you think you know what it will do, copy the text of the program into the python tutor and visualize its execution. Here are some things to note as you run the program:
main()
is run, a blue box is put on "top" of the stack,
with any variables declared in main()
shown in the box (or
with arrows pointing to the data of the variable)capitalize()
is called from main()
, another blue box
is put on "top" of the stack. The function on top of the stack
is the function that is currently executingcapitalize()
, the mylist
variable points to the same data
that L
in main()
points to. This means any changes made to
mylist[i]
will affect L
in main()
isVowel()
is called, there is a blue box for it put
on top of the stack. When isVowel()
ends, the box (and all variables
in the box!) disappears and we drop back to capitalizeVowels()
, the
function that called isVowel()
The final output of the program is this:
5
wE lOvE cOmp scI!
Do you understand how L
was changed in main()
, even though capitalizeVowels()
did not return mylist
?
We also went over Quiz 2 today. See quiz2.py
in your c21/examples
directory.