7.1 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 abs(num):
    if num < 0:
        num = -num
    return num

if abs(a) == 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 abs. Next comes a ( followed by the parameter num (num is passed from the program from wherever it is called to the function). 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 how a return is optional.

Functions can be used to eliminate repeat code.