Try the Jupyter notebook version.


As our programs get larger and more complex, using functions becomes a neccessity. Designing and writing your programs using functions makes them easier to write, read, and debug.


Just like we've been doing all along with main(), a function is just an indented block of code with a name. Here's a simple function:

def happybirthday(name):
  """display happy birthday song for name"""
  print("Happy Birthday to you.")
  print("Happy Birthday to you.")
  print("Happy Birthday, dear %s." % (name))
  print("Happy Birthday to you!")


Some things to note about the above function:

Here's an example of how the above function might be called from main():

def main():
  name = input("Who's birthday is it? ")

Whatever the user types in, it is stored in the variable name. That data is then sent to the function, for use in the print statements. In main(), the variable name is used as an argument in the call to the happybirthday() function. When writing and calling functions, the number of arguments must match the number of parameters.

I also don't have to use a variable as an argument. I could just use a string argument, like this:


which would print:

  Happy Birthday to you.
  Happy Birthday to you.
  Happy Birthday, dear Ravi.
  Happy Birthday to you!


Suppose we have a list of numbers and want to calculate the average of all numbers in the list. For example, in main(), I might have a list of quiz grades:

quizzes = [9,8,9.5,10,10,7,7.5,9,8,9,9]

If I write a function, called average(), I could call that function from main(), have it do the calculation, and then get the result back in main().

Here's one way to write the function:

def average(mylist):
  """calculate and return average of numbers in a list"""

  total = 0.0
  for num in mylist:
    total = total + num
  ave = total/len(mylist)

  return ave

The full main() might look like this:

def main():
  quizzes = [9,8,9.5,10,10,7,7.5,9,8,9,9]
  quizave = average(quizzes)
  print("Average quiz grade = %.2f" % (quizave))

A few things to note:


Write a function called count(phrase,ch) that has two parameters: a string (phrase) and a character (ch). The function should count and return how many times ch is found in phrase. For example:

CS21 Topics