Week 6, Monday: Fruitful Functions

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.

python lists and functions

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)

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
    return False


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:

python tutor image

The final output of the program is this:

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.