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!")
return
Some things to note about the above function:
name
variableprint
statementsreturn
at the end signals the end of the function, but is not
always necessaryHere's an example of how the above function might be called from
main()
:
def main():
name = raw_input("Who's birthday is it? ")
happybirthday(name)
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:
happybirthday("Ravi")
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:
main()
is nice and shortquizzes
mylist
average()
function does the work, and then returns the result
back to main()
quizave
in
main()
main()
and the function: the
quizzes
list is sent to the function, the ave
calculated is
sent back to main()
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:
count("hello","e")
should return 1
count("mississippi","i")
should return 4
count("SWARTHMORE","z")
should return 0