






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







4.10 Fruitful functions and void functions
Some of the functions we are using, such as the math functions, yield results; for lack of a better name, I call them fruitful functions. Other functions, like print_twice, perform an action but don’t return a value. They are called void functions.
When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression:
x = math.cos(radians) golden = (math.sqrt( 5 ) + 1 ) / 2
When you call a function in interactive mode, Python displays the result:
>>> math.sqrt( 5 )
But in a script, if you call a fruitful function and do not store the result of the function in a variable, the return value vanishes into the mist!
math.sqrt( 5 )
This script computes the square root of 5, but since it doesn’t store the result in a variable or display the result, it is not very useful.
Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None.
>>> result = print_twice('Bing') Bing Bing >>> print(result) None
The value None is not the same as the string “None”. It is a special value that has its own type:
>>> print(type(None)) < class 'NoneType'>
To return a result from a function, we use the return statement in our function. For example, we could make a very simple function called addtwo that adds two numbers together and returns a result.
Also, don’t forget to save your program before you run it. Some development environments do this automatically, but some don’t. In that case, the program you are looking at in the text editor is not the same as the program you are running. Debugging can take a long time if you keep running the same incorrect program over and over! Make sure that the code you are looking at is the code you are running. If you’re not sure, put something like print("hello") at the beginning of the program and run it again. If you don’t see hello, you’re not running the right program!
4.13 Glossary
algorithm A general process for solving a category of problems.
argument A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
body The sequence of statements inside a function definition.
composition Using an expression as part of a larger expression, or a statement as part of a larger statement.
deterministic Pertaining to a program that does the same thing each time it runs, given the same inputs.
dot notation The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.
flow of execution The order in which statements are executed during a program run.
fruitful function A function that returns a value.
function A named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.
function call A statement that executes a function. It consists of the function name followed by an argument list.
function definition A statement that creates a new function, specifying its name, parameters, and the statements it executes.
function object A value created by a function definition. The name of the func- tion is a variable that refers to a function object.
header The first line of a function definition.
import statement A statement that reads a module file and creates a module object.
module object A value created by an import statement that provides access to the data and code defined in a module.
parameter A name used inside a function to refer to the value passed as an argument.
pseudorandom Pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program.
return value The result of a function. If a function call is used as an expression, the return value is the value of the expression.
void function A function that does not return a value.
4.14 Exercises
Exercise 4: What is the purpose of the “def” keyword in Python?
a) It is slang that means “the following code is really cool” b) It indicates the start of a function c) It indicates that the following indented section of code is to be stored for later d) b and c are both true e) None of the above
Exercise 5: What will the following Python program print out?
A common pattern in assignment statements is an assignment statement that up- dates a variable, where the new value of the variable depends on the old.
x = x + 1
This means “get the current value of x, add 1, and then update x with the new value.”
If you try to update a variable that doesn’t exist, you get an error, because Python evaluates the right side before it assigns a value to x:
>>> x = x + 1 NameError: name 'x' is not defined
Before you can update a variable, you have to initialize it, usually with a simple assignment:
>>> x = 0 >>> x = x + 1
Updating a variable by adding 1 is called an increment ; subtracting 1 is called a decrement.
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Because iteration is so common, Python provides several language features to make it easier. One form of iteration in Python is the while statement. Here is a simple program that counts down from five and then says “Blastoff!”.
n = 10 while True: print(n, end=' ') n = n - 1 print('Done!')
If you make the mistake and run this code, you will learn quickly how to stop a runaway Python process on your system or find where the power-off button is on your computer. This program will run forever or until your battery runs out because the logical expression at the top of the loop is always true by virtue of the fact that the expression is the constant value True.
While this is a dysfunctional infinite loop, we can still use this pattern to build useful loops as long as we carefully add code to the body of the loop to explicitly exit the loop using break when we have reached the exit condition. For example, suppose you want to take input from the user until they type done. You could write:
while True: line = input('> ') if line == 'done': break print(line) print('Done!')
# Code: http://www.pythonlearn.com/code3/copytildone1.py
The loop condition is True, which is always true, so the loop runs repeatedly until it hits the break statement. Each time through, it prompts the user with an angle bracket. If the user types done, the break statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop. Here’s a sample run:
> hello there hello there > finished finished > done Done!
This way of writing while loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (“stop when this happens”) rather than negatively (“keep going until that happens.”).
5.5 Finishing iterations with continue
Sometimes you are in an iteration of a loop and want to finish the current iteration and immediately jump to the next iteration. In that case you can use the continue
statement to skip to the next iteration without finishing the body of the loop for the current iteration.
Here is an example of a loop that copies its input until the user types “done”, but treats lines that start with the hash character as lines not to be printed (kind of like Python comments).
while True: line = input('> ') if line[ 0 ] == '#': continue if line == 'done': break print(line) print('Done!')
# Code: http://www.pythonlearn.com/code3/copytildone2.py
Here is a sample run of this new program with continue added.
> hello there hello there > # don't print this > print this! print this! > done Done!
All the lines are printed except the one that starts with the hash sign because when the continue is executed, it ends the current iteration and jumps back to the while statement to start the next iteration, thus skipping the print statement.
5.6 Definite loops using for
Sometimes we want to loop through a set of things such as a list of words, the lines in a file, or a list of numbers. When we have a list of things to loop through, we can construct a definite loop using a for statement. We call the while statement an indefinite loop because it simply loops until some condition becomes False, whereas the for loop is looping through a known set of items so it runs through as many iterations as there are items in the set.
The syntax of a for loop is similar to the while loop in that there is a for statement and a loop body:
friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends: print('Happy New Year:', friend) print('Done!')