Week 4, Monday: Functions I

review of Quiz 1

See the q1.py file in your w04 directory. If you don't understand one of the quiz questions, try writing out the code in q1.py. I expect you to understand everything from the quizzes. Please ask if you have questions.

functions

In the q1.py program is the following function:

def printline(text):
  char = "#"
  print("\n %s %s %s \n" % (char*10, text, char*20))

and it is called from main() like this:

printline("Q1")

This is a simple function with one parameter, text. When it is called in main(), there is one argument given inside the parentheses (the string, "Q1"). For functions, the number of parameters must match the number of arguments, and in the above printline() function, the parameter is assigned to the argument, as if this occurred:

text = "Q1"

The above function is fairly simple -- it just prints out a line, and there is no return value.

adventure example

Just like you wouldn't write a paper with only one long paragraph, we don't write long programs with only a main() function. Breaking our programs up into functions has many benefits:

For example, here's the main() function for the adventure.py program I showed you last week:

def main():
  """adventure game"""

  printintro()
  choice = getchoice(1,3)
  if choice == 1:           ###############
    evilninja()
    choice = getchoice(1,4)
    if choice == 2:
      winner()
    else:
      death()
  elif choice == 2:         ###############
    sprainankle()
    choice = getchoice(1,3)
    if choice == 2:
      cplus()
    else:
      death()
  elif choice == 3:         ###############
    badhair()
    choice = getchoice(1,3)
    if choice == 3:
      cplus()
    else:
      death()
  else:                     ###############
    death()

This is a relatively small program, but it still has 6-8 functions. Since many paths lead to the same outcome (death() or cplus()), it's useful to write those as functions, instead of inserting the same print statements in multiple places. This also makes main() shorter and easier to read.

The getchoice() function is used wherever we want to get a numerical choice from the user, like a menu with options 1-4. This function, although not shown, takes two arguments, the low and the high menu choice. Once we learn indefinite loops, we can write a function like getchoice(), that asks the user for a choice and then checks to make sure the input choice is valid (asking again and again, until we get valid input).

terminology

Terminology related to functions:

For example:

sum a list

Let's write a simple function to sum the integers in a list. Here's how I would like to call it from main():

def main():
  L = [-1,-2,-3]
  total = sumList(L)
  print(L)
  print(total)

And here's how the function might look:

def sumList(mylist):
  """sum numbers in list and return result"""

  sumoflist = 0
  for num in mylist:
    sumoflist = sumoflist + num
  return sumoflist

When this is called from main(), the parameter mylist is assigned to L, and the function just sums up all values in the list. After the for loop, it then returns the result back to main(), where it is assigned to the variable total.

your turn!

Write a function to count letters. Here's how I would like to call it in main():

def main():
  phrase = raw_input("phrase: ")
  letter = raw_input("letter: ")
  n = count(letter, phrase)
  print("Number of %s's in that phrase: %d" % (letter, n))