functions (more details)


Understanding stack diagrams helps you understand how the computer works, and why python does what it does. It will also be vary valuable in week 10 when we learn recursion (functions calling multiple copies of themselves).


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

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?


Write a function called listmax(L,maxval) that has two parameters: a list (L) of numbers and a maximum value (maxval). The function should reset any values in L that are above maxval. For example:

CS21 Topics