Calling Functions

Calling Functions: Parameters and Return Values

A function does some work for us. We can send a function some data, and it will perform some task and send us something back.

Consider the function sqrt. A program can send it a number and get something back:

    result = sqrt(16)

When you call a function, you sometimes send it some data that it needs to do its job. We call such data a parameter. 16 is the parameter sent to sqrt in the sample above. Parameters are placed in parenthesis after the function name.

Sometimes functions return you some data when they complete. We call such data a return value. We say that the calling function catches the return value. In the sample above, the return value is caught by the variable result.

Some functions are built-in to the Python language. sqrt is one example. The input() function is another that you are familiar with.

Other functions are just sub-programs written by some programmer-- named pieces of code that you can call. Anyone can write such functions using the 'def' statement. For example, I could create a function cube:

    def cube(x):
        return x*x*x

and then call it:

    result = cube(3)

In the JES Media Introduction tutorial, you called some functions:

    fileName= pickAFile()                                                     # this asks the end-user to choose a graphic file
    pic = makePicture(fileName)                                        # this creates a picture in memory holding the pixels of the image.
    show(pic)                                                                            # this draws the picture on the screen

    addLine(pic,0,0,200,200)                                             # draw a line going from coordinate (0,0) to (200,200)
    addText(pic,100,100,"hey dude")                               # draw some text at coordinate (100,100)
    repaint(pic)                                                                        # this will render the picture with the changes.  

The makePicture function has one parameter, fileName. You tell makePicture a fileName, and it loads a picture for you (in memory). That picture is returned to your program and 'caught' in the variable pic.

In-Class Worksheet
1. What are the parameters of the other JES function calls above? Which need to catch a return value?




2. The JES Help provides a list of function definitions, also known as an application programmer interface (API). Open JES and find the definition for the function addLine. What are the names for the five parameters it expects sent to it? How would you call it to draw a vertical line all the way down the middle of a picture?



3. If you were going to write a function for computing the new principal for a bank account after n years, what would be the parameters? What would it return?

Recent site activity