Defining Functions

Defining Functions next up previous contents
Next: Lists Up: Non-Programmers Tutorial For Python Previous: Debugging   Contents

Subsections

Creating Functions

To start off this chapter I am going to give you a example of what you could do but shouldn't (so don't type it in):
a = 23
b = -23

if a < 0:
    a = -a

if b < 0:
    b = -b

if a == b:
    print "The absolute values of", a,"and",b,"are equal"
else:
    print "The absolute values of a and b are different"
with the output being:
The absolute values of 23 and 23 are equal
The program seems a little repetitive. (Programmers hate to repeat things (That's what computers are for aren't they?)) Fortunately Python allows you to create functions to remove duplication. Here's the rewritten example:
a = 23
b = -23

def my_abs(num):
    if num < 0:
        num = -num
    return num

if my_abs(a) == my_abs(b):
    print "The absolute values of", a,"and",b,"are equal"
else:
    print "The absolute values of a and b are different"
with the output being:
The absolute values of 23 and -23 are equal
The key feature of this program is the def statement. def (short for define) starts a function definition. def is followed by the name of the function my_abs. Next comes a ( followed by the parameter num (num is passed from the program into the function when the function is called). The statements after the : are executed when the function is used. The statements continue until either the indented statements end or a return is encountered. The return statement returns a value back to the place where the function was called.

Notice how the values of a and b are not changed. Functions of course can be used to repeat tasks that don't return values. Here's some examples:

def hello():
    print "Hello"

def area(width,height):
    return width*height

def print_welcome(name):
    print "Welcome",name

hello()
hello()

print_welcome("Fred")
w = 4
h = 5
print "width =",w,"height =",h,"area =",area(w,h)
with output being:
Hello
Hello
Welcome Fred
width = 4 height = 5 area = 20
That example just shows some more stuff that you can do with functions. Notice that you can use no arguments or two or more. Notice also when a function doesn't need to send back a value, a return is optional.

Variables in functions

Of course, when eliminiating repeated code, you often have variables in the repeated code. These are dealt with in a special way in Python. Up till now, all variables we have see are global variables. Functions have a special type of variable called local variables. These variables only exist while the function is running. When a local variable has the same name as another variable such as a global variable, the local variable hides the other variable. Sound confusing? Well, hopefully this next example (which is a bit contrived) will clear things up.

a_var = 10
b_var = 15
e_var = 25

def a_func(a_var):
    print "in a_func a_var = ",a_var
    b_var = 100 + a_var
    d_var = 2*a_var
    print "in a_func b_var = ",b_var
    print "in a_func d_var = ",d_var
    print "in a_func e_var = ",e_var
    return b_var + 10

c_var = a_func(b_var)

print "a_var = ",a_var
print "b_var = ",b_var
print "c_var = ",c_var
print "d_var = ",d_var

The output is:

in a_func a_var =  15
in a_func b_var =  115
in a_func d_var =  30
in a_func e_var =  25
a_var =  10
b_var =  15
c_var =  125
d_var =
Traceback (innermost last):
  File "separate.py", line 20, in ?
    print "d_var = ",d_var
NameError: d_var

In this example the variables a_var, b_var, and d_var are all local variables when they are inside the function a_func. After the statement return b_var + 10 is run, they all cease to exist. The variable a_var is automatically a local variable since it is a parameter name. The variables b_var and d_var are local variables since they appear on the left of an equals sign in the function in the statements b_var = 100 + a_var and d_var = 2*a_var .

Inside of the function a_var is 15 since the function is called with a_func(b_var). Since at that point in time b_var is 15, the call to the function is a_func(15) This ends up setting a_var to 15 when it is inside of a_func.

As you can see, once the function finishes running, the local variables a_var and b_var that had hidden the global variables of the same name are gone. Then the statement print "a_var = ",a_var prints the value 10 rather than the value 15 since the local variable that hid the global variable is gone.

Another thing to notice is the NameError that happens at the end. This appears since the variable d_var no longer exists since a_func finished. All the local variables are deleted when the function exits. If you want to get something from a function, then you will have to use return something.

One last thing to notice is that the value of e_var remains unchanged inside a_func since it is not a parameter and it never appears on the left of an equals sign inside of the function a_func. When a global variable is accessed inside a function it is the global variable from the outside.

Functions allow local variables that exist only inside the function and can hide other variables that are outside the function.

Function walkthrough

TODO Move this section to a new chapter, Advanced Functions.

Now we will do a walk through for the following program:

def mult(a,b):
    if b == 0:
        return 0
    rest = mult(a,b - 1)
    value = a + rest
    return value

print "3*2 = ",mult(3,2)

Basically this program creates a positive integer multiplication function (that is far slower than the built in multiplication function) and then demonstrates this function with a use of the function.

Question: What is the first thing the program does?

Answer: The first thing done is the function mult is defined with the lines:

def mult(a,b):
    if b == 0:
        return 0
    rest = mult(a,b - 1)
    value = a + rest
    return value
This creates a function that takes two parameters and returns a value when it is done. Later this function can be run.

Question: What happens next?

Answer: The next line after the function, print "3*2 = ",mult(3,2) is run.

Question: And what does this do?

Answer: It prints 3*2 = and the return value of mult(3,2)

Question: And what does mult(3,2) return?

Answer: We need to do a walkthrough of the mult function to find out.

Question: What happens next?

Answer: The variable a gets the value 3 assigned to it and the variable b gets the value 2 assigned to it.

Question: And then?

Answer: The line if b == 0: is run. Since b has the value 2 this is false so the line return 0 is skipped.

Question: And what then?

Answer: The line rest = mult(a,b - 1) is run. This line sets the local variable rest to the value of mult(a,b - 1). The value of a is 3 and the value of b is 2 so the function call is mult(3,1)

Question: So what is the value of mult(3,1) ?

Answer: We will need to run the function mult with the parameters 3 and 1.

Question: So what happens next?

Answer: The local variables in the new run of the function are set so that a has the value 3 and b has the value 1. Since these are local values these do not affect the previous values of a and b.

Question: And then?

Answer: Since b has the value 1 the if statement is false, so the next line becomes rest = mult(a,b - 1).

Question: What does this line do?

Answer: This line will assign the value of mult(3,0) to rest.

Question: So what is that value?

Answer: We will have to run the function one more time to find that out. This time a has the value 3 and b has the value 0.

Question: So what happens next?

Answer: The first line in the function to run is if b == 0: . b has the value 0 so the next line to run is return 0

Question: And what does the line return 0 do?

Answer: This line returns the value 0 out of the function.

Question: So?

Answer: So now we know that mult(3,0) has the value 0. Now we know what the line rest = mult(a,b - 1) did since we have run the function mult with the parameters 3 and 0. We have finished running mult(3,0) and are now back to running mult(3,1). The variable rest gets assigned the value 0.

Question: What line is run next?

Answer: The line value = a + rest is run next. In this run of the function, a=3 and rest=0 so now value=3.

Question: What happens next?

Answer: The line return value is run. This returns 3 from the function. This also exits from the run of the function mult(3,1). After return is called, we go back to running mult(3,2).

Question: Where were we in mult(3,2)?

Answer: We had the variables a=3 and b=2 and were examining the line rest = mult(a,b - 1) .

Question: So what happens now?

Answer: The variable rest get 3 assigned to it. The next line value = a + rest sets value to 3+3 or 6.

Question: So now what happens?

Answer: The next line runs, this returns 6 from the function. We are now back to running the line print "3*2 = ",mult(3,2) which can now print out the 6.

Question: What is happening overall?

Answer: Basically we used two facts to calulate the multipule of the two numbers. The first is that any number times 0 is 0 (x * 0 = 0). The second is that a number times another number is equal to the first number plus the first number times one less than the second number (x * y = x + x * (y - 1)). So what happens is 3*2 is first converted into 3 + 3*1. Then 3*1 is converted into 3 + 3*0. Then we know that any number times 0 is 0 so 3*0 is 0. Then we can calculate that 3 + 3*0 is 3 + 0 which is 3. Now we know what 3*1 is so we can calculate that 3 + 3*1 is 3 + 3 which is 6.

This is how the whole thing works:

3*2
3 + 3*1
3 + 3 + 3*0
3 + 3 + 0
3 + 3
6

These last two sections were recently written. If you have any comments, found any errors or think I need more/clearer explanations please email. I have been known in the past to make simple things incomprehensible. If the rest of the tutorial has made sense, but this section didn't, it is probably my fault and I would like to know. Thanks.

Examples

factorial.py

#defines a function that calculates the factorial

def factorial(n):
    if n <= 1:
        return 1
    return n*factorial(n-1)

print "2! = ",factorial(2)
print "3! = ",factorial(3)
print "4! = ",factorial(4)
print "5! = ",factorial(5)

Output:

2! =  2
3! =  6
4! =  24
5! =  120

temperature2.py

#converts temperature to fahrenheit or celsius

def print_options():
    print "Options:"
    print " 'p' print options"
    print " 'c' convert from celsius"
    print " 'f' convert from fahrenheit"
    print " 'q' quit the program"

def celsius_to_fahrenheit(c_temp):
    return 9.0/5.0*c_temp+32

def fahrenheit_to_celsius(f_temp):
    return (f_temp - 32.0)*5.0/9.0

choice = "p"
while choice != "q":
    if choice == "c":
        temp = input("Celsius temperature:")
        print "Fahrenheit:",celsius_to_fahrenheit(temp)
    elif choice == "f":
        temp = input("Fahrenheit temperature:")
        print "Celsius:",fahrenheit_to_celsius(temp)
    elif choice != "q":
        print_options()
    choice = raw_input("option:")

Sample Run:

> python temperature2.py
Options:
 'p' print options
 'c' convert from celsius
 'f' convert from fahrenheit
 'q' quit the program
option:c
Celsius temperature:30
Fahrenheit: 86.0
option:f
Fahrenheit temperature:60
Celsius: 15.5555555556
option:q

area2.py

#By Amos Satterlee
print
def hello():
    print 'Hello!'

def area(width,height):
    return width*height

def print_welcome(name):
    print 'Welcome,',name

name = raw_input('Your Name: ')
hello(),
print_welcome(name)
print
print 'To find the area of a rectangle,'
print 'Enter the width and height below.'
print
w = input('Width:  ')
while w <= 0:
    print 'Must be a positive number'
    w = input('Width:  ')
h = input('Height: ')
while h <= 0:
    print 'Must be a positive number'
    h = input('Height: ')
print 'Width =',w,' Height =',h,' so Area =',area(w,h)

Sample Run:

Your Name: Josh
Hello!
Welcome, Josh

To find the area of a rectangle,
Enter the width and height below.

Width:  -4
Must be a positive number
Width:  4
Height: 3
Width = 4  Height = 3  so Area = 12

Exercises

Rewrite the area.py program done in 3.2 to have a separate function for the area of a square, the area of a rectangle, and the area of a circle. (3.14 * radius**2). This program should include a menu interface.


next up previous contents
Next: Lists Up: Non-Programmers Tutorial For Python Previous: Debugging   Contents
Josh Cogliati jjc@honors.montana.edu Wikibooks Version: Wikibooks Non-programmers Python Tutorial Contents