Function -- A named sequence of statements that perform a task.

def someTask():

statement1
statement2
...

Parameters-- Data sent to a function. The function signature names the parameters within parenthesis after function name. Parameters allow a function to be reusable on different data sets.

def someTask(param1,param2):

statement1
statement2
...

Function call-- When another part of the program invokes execution of a function.

someTask("joe",x)
nextStatement
...

We say that the calling function calls the function to perform its duties, and sends the required parameters. After the function completes, control resumes after the function call.

Note that the actual data sent to the function need not be named the same as the parameter names, e.g., 'x' maps to param2 but is not named the same.

Return value- Data returned from a function with a return statement.

def someTask(param1,param2):

statement1
statement2
...
return something

result = someTask("joe",x)

Note that the name of the return variable need not be the same as the variable that catches the return value.

Effect of a function -- A function can 1) modify parameters, 2) return a value, 3) print something.

 

 

 

Let's look at some examples:

Bank Account -- Consider the following program:

balance = input("Please enter balance");
rate = input("please enter rate as a decimal");
newBalance = balance + (balance*rate)
print newBalance

There is one function call in the program, to a library function. What is it? What do you think the function definition for that library function looks like?

Rewrite the program so that computing the new balance is a function. What should the parameters be? What should be returned? Here's the solution.

Factorial -- Consider the factorial program:

total = 1
multiplier = input('Please enter n:')

while (multiplier>1):

total=total*multiplier
multiplier=multiplier-1

print total

Write it as a function, and call it in the main program. Here's the solution.

More complex functions

Consider the following JES program that draws a white box on an image:

name=pickAFile()
pic=makePicture(name)
show(pic)
color=makeColor(255,255,255)  # white
max=100
x=1
while x <max:
    y=1
    while y < max:
        pixel=getPixel(pic,x,y)
        setColor(pixel,color)
        y=y+1
    x=x+1
repaint(pic)

What are the function calls in this program? Write out a function signature for each.