Functions

A function is a named sequence of statements that performs a desired operation. 
 
When you brush your teeth in the morning, you 
 
1) open the cabinet, 
2) grab your brush and paste, 
3) put some paste on your brush, 
4) open your mouth, 
5) push the brush across your teeth. 
 
Think of this sequence of steps as a function.
 
Now when a dad tells a kid to brush his teeth, he doesn’t want to explain all these steps each time. When the dad says, “brush your teeth”, he is making a function call. 
 
‘Brush your teeth’ is an abstraction for all the many steps involved.
 
The top software engineers often don't write a lot of code directly. They just design giant pieces of software, working at the structure chart level (or UML level for object-oriented programs).
 
The goal is to divide and conquer, to break the problem down into parts small enough that it easy to program. You also want to create reusable components that can be used in many different software applications.

Calling Built-in Functions

Python provides a number of built-in functions. For instance, the 'len' function returns the length of a list:
 
    while i<len(list):

The bolded part of the statement above is a function call.

Functions in programming are like math functions: you provide the name of the function, e.g., 'len', followed by an open parenthesis, and then some parameters (e.g., list) and then a closed parenthesis.
 
The function returns a value to the caller. In the example above, the returned value is part of a condition. Other times, you'll want to "catch" the return value in a variable, e.g.,
 
    length = len(list1)

Importing Modules

len is a function built-in to the Python language. There are also many libraries of functions that you can 'import' into your programs.
You call 'import modname' at the top of your program, and then you can use its functions. One popular module is the math module, which
has numerous mathematical functions such as sqrt:
 
    import math   # put this at top of file

    result= math.sqrt(16)
 
The import statement says you want to use math functions. But when you import a module, like 'math', you must qualify any function calls you make to functions with "math." For the above example, if you typed in just 'sqrt(16)' you'd get an error.

'math.sqrt(16)' is understandable to Python because it knows that sqrt is within the math module.
 
Other math functions include:
 
math.pow (x,y) -- returns x to the yth power, so pow(2,3) is 8
math.acos(x) – returns cosine of x
 
A description of all the functions in the math module is at: http://docs.python.org/lib/module-math.html

Another module often used for games is the random module.

This module provides numerous functions, including randint(min,max) which returns a random number between min and max inclusive:
 
    import random # at top of program
    # ...
    number = random.randint(0,10)   # will return a random number 0 through 10
 
In this case, 'random' is the module name, and 'randint' is the function name.
 
Let's play around with randint by writing a loop that calls it and prints the result:
 
import random
i=0
while i<20:
 
    number = random.randint(0,5)
    print number
    i=i+1
 
What is printed?
 
Note that the randint function returns integers. If you wanted, say, to get a random choice from a set of possible colors, you have to perform some coding work on your own to convert each random integer to a corresponding color.

In-Class Assignment

1. Write a program that accepts a number and exponent from the end-user and prints numberexponent
2. Write a program that generates and prints a random color from a set of six colors.

Writing Your Own Functions

A function is basically a list of commands. By assigning a name to a bunch of commands, we create an abstraction that can be used in a larger program. Here is an example of a function in Python:
 
    def totalList(list):
       i=0
       total=0
       while i<len(list):
            total=total+list[i]
            i=i+1
       return total

totalList is the function name. 'list' is a formal parameter.
 
By defining 'totalList' we can then call it-- from anywhere in our program-- whenever we need to total a list (instead of copy-paste).
 
The caller of the function must supply the correct number of parameters in the function call, and those parameters must be of the same type for the function to work correctly. For instance, the totalList function expects a list of numbers, so here is a valid call to it:
 
    numbers=[2,5,7]
    result = totalList(numbers)

The data sent to a function are called the 'actual parameters'. So the variable 'numbers' in the above code is the actual parameter sent to totalList.

Important: the actual parameter names need not match the formal parameter names. All that matters is the order the parameters are listed.

If one called totalList with the wrong number or type of parameters, the program will either stop executing or behave strangely. Consider what occurs with the following calls:

    result=totalList(7)
    names=['ralph','sara']
    result=totalList(names)
    totalList([4,5])

Return values

A function can return a value to the calling code with the 'return' statement. This is often the last statement in the function. The calling code must 'catch' the return value in a variable, e.g., the variable total is 'catching' the return value of totalList:
 
list=[3,5,2]
total = totalList(list)
 
But as you saw with the 'len' function, sometimes a function is called is part of another construct, like a condition:

           while (i<len(list))

Here the result is not caught by a variable, it just is used to evaluate the condition.

With functions, one can break a program into simple parts. A typical Python program will have several functions and a 'main' body of code, as below:
 
    def func1(param1,param2):
    #...
 
    def func2(param1):
    #...
 
    #... more functions
 
    # main code just starts with no indentation
    #...

In-Class Assignment 2

1. In a file mymath.py, write a function 'cube(x)' which returns the cube of the parameter x--  (x3). The file's ‘main’ code should call 'cube(x)' a couple of times, with different actual parameters, and print the results. 
 
2. Write a function 'getGuess' that asks the user to input four colors and returns the four colors in a list. Call your function from the 'main' program and print out the list.

3. Write a function 'getSecretCode' that returns a randomly generated list of colors. Call this function from the main program and print out the list.


Recent site activity