More Loops and Functions


A function is a named sequence of statements.

Functions can reduce repetition of the same code in multiple locations in a program.


Example: Suppose you want to write a program that prints the "happy birthday song". You could do this:



def main(): #give a name to these statements
    print 'Happy birthday to you!'
    print 'Happy birthday to you!'
    print 'Happy birthday, dear Elvis,'
    print 'Happy birthday to you!'

main()   # actually execute the main function


What's Wrong with It?


But this contains a lot of repeated code - namely, the 1st, 2nd and 4th lines are identical.


So let's write a function that prints that repeated line. 


Removing Repetition


#Defining (but not calling) the main function
def main():
    singHappy()
    singHappy()
    print 'Happy birthday, dear Elvis,'
    singHappy()

# defining (not calling) singHappy()
def singHappy():
    print 'Happy birthday, to you!'

main() # execute main function


Adding Flexibility with Parameters



Note: It would be nice if we could sing the song to anyone, rather than just Elvis. We can achieve this by writing a function that uses a parameter to produce the 3rd line of the song.


A parameter is a variable which is initialized when the function is called.



New version of the program:

def main():
    singIt("Elvis")
    print  # blank line
    singIt("Nancy")

def singIt(person):
    singHappy()
    singHappy()
    print 'Happy birthday, dear', person + ','
    singHappy()

def singHappy():
    print 'Happy birthday to you!'

main() # execute main

# read the user's name and sing the song
# to them.
name = raw_input("What is your name? ")
singIt(name)

Output:
Happy birthday to you!
Happy birthday to you!
Happy birthday dear Elvis,
Happy birthday to you!

Happy birthday to you!
Happy birthday to you!
Happy birthday dear Nancy,
Happy birthday to you!
What is your name? Gwen
Happy birthday to you!
Happy birthday to you!
Happy birthday dear Gwen,
Happy birthday to you!



How parameters work


General form of a function definition:
def functionName(parameter1, parameter2, ...):
        statement
        statement
        etc. # body of function






Functions that return values


Some functions return a value when they are called. For example, the sqrt() function in the math library:

# 9 is the argument for math.sqrt()
root = math.sqrt(9)


The function math.sqrt() returns a value that is assigned to the variable root.


Example:
def times3(number):
    return 3*number

We can call this function like this:
answer = times3(7)  # answer is 21


Exercise:
Write a function that takes 3 numbers as arguments, and returns the product of the 3 numbers. Then write a main function that calls this function for the following values:
1, 2, 3
2, 3, 4
3, 4, 5
4, 5, 6
...
20, 21, 22