• No results found

Just as with mathematical functions, Python functions can be composed, meaning that you use the result of one function as the input to another.

>>> print_twice(abs(-7)) 7 7

>>> print_twice(max(3, 1, abs(-11), 7)) 11 11

In the first example, abs(-7) evaluates to 7, which then becomes the argument to print twice. In the second example we have two levels of composition, since abs(-11) is first evaluated to 11 before max(3, 1, 11, 7)is evaluated to 11 and print twice(11) then displays the result.

We can also use a variable as an argument:

>>> michael = 'Eric, the half a bee.'

>>> print_twice(michael)

Eric, the half a bee. Eric, the half a bee.

Notice something very important here. The name of the variable we pass as an argument (michael) has nothing to do with the name of the parameter (bruce). It doesn’t matter what the value was called back home (in the caller); here in print twice, we call everybody bruce.

4.6

Glossary

function: A named sequence of statements that performs some useful operation. Functions may or may not take parameters and may or may not produce a result.

function definition: A statement that creates a new function, specifying its name, parameters, and the statements it executes.

compound statement: A statement that consists of two parts:

1. header - which begins with a keyword determining the statement type, and ends with a colon. 2. body - containing one or more statements indented the same amount from the header.

The syntax of a compound statement looks like this:

keyword expression : statement

statement ...

header: The first part of a compound statement. Headers begin with a keyword and end with a colon (:)

body: The second part of a compound statement. The body consists of a sequence of statements all in- dented the same amount from the beginning of the header. The standard amount of indentation used within the Python community is 4 spaces.

flow of execution: The order in which statements are executed during a program run.

parameter: A name used inside a function to refer to the value passed as an argument.

argument: A value provided to a function when the function is called. This value is assigned to the corre- sponding parameter in the function.

abs function: Returns the absolute value of the argument.

pow function: Returns the first argument raised to the power of the second one, equivalent to x**y.

max function: Returns the largest argument (if given more than one), or the largest item in a sequence (if given a single sequence).

>>> max(3, 8, 2, 1) 8

>>> max([2, 0, 9, 4]) 9

function composition: Using the output from one function call as the input to another.

4.7

Laboratory exercises

1. Using IDLE, create a Python script named functions.py. Type the definition of the function new linefrom the lecture at the top of the file, and then add the definition of the function three lines below it. Run the program (it won’t seem to do anything), and then change to the interpreter window and call three lines to check that it works as expected.

2. Add a function to the file called nine lines that uses three lines to print nine blank lines. Now add a function named clear screen that prints out forty blank lines. The last line of your program should be a call to clear screen.

3. Move the last line of functions.py to the top of the program, so the function call to clear screen appears before the function definition. Run the program and record the error message you get.



zend



4. State a rule about function definitions and function calls which describes where they can appear relative to each other in a program?



zend



5. Starting with a working version of functions.py, move the definition of new line after the defi- nition of three lines. Record what happens when you run this program. Now move the definition of new line below a call to three lines(). Explain how this is an example of the rule you stated in the previous exercise.



zend



6. One of the reasons functions are useful is that they help to avoid needless repetition. Instead of using copy and paste to duplicate the same lines of code many times in a program, we wrap the lines we want in a function and then call that function whenever we need to. Avoiding repetition also means we don’t have to type the same commands over and over again. Let’s say we have a list of numbers and we want to print out some information about it.

>>> nums = [4, 9, 3, 17, 21, 6, 14] >>> min(nums) 3 >>> max(nums) 21 >>> sum(nums) 74 >>> float(sum(nums))/len(nums) 10.571428571428571

The only new function here is sum which (not surprisingly) returns the sum of a list of numbers. If we were regularly printing out this information for different lists of numbers it would be sensible to define a function which printed out a summary of what we wanted to know. Write a function which when called like this info(nums) prints out something like this:

Min: 3, Max: 21, Sum: 74, Average: 10.571428571428571

7. Try to complete up to level seven on the game you played in the previous labs.

Lecture 5

Functions: part 2

Remember the print twice function from the previous lecture? We are going to use it again, but we will change the parameter name to something a bit more sensible.

def print_twice(phrase):

print phrase, phrase

5.1

Variables and parameters are local

When you create a local variable inside a function, it only exists inside the function, and you cannot use it outside. For example:

def print_joined_twice(part1, part2): joined = part1 + part2

print_twice(joined)

This function takes two arguments, concatenates them, and then prints the result twice. We can call the function with two strings:

>>> line1 = "Happy birthday, "

>>> line2 = "to you."

>>> print_joined_twice(line1, line2)

Happy birthday, to you. Happy birthday, to you.

When print joined twice terminates, the variable joined is destroyed. If we try to print it, we get an error:

>>> print joined

NameError: name 'joined' is not defined

Parameters are also local. For example, outside the function print twice, there is no such thing as phrase. If you try to use it, Python will complain.