LearnWave
Learn it. Master it.

Functions

Returning values and flow of execution

Return a value from a function and use it.

The return statement sends control back to the place where the function was called, together with a value. A function with no return statement (or a bare return) gives back None. Functions that only display results and return nothing are called void functions.

For example, the book's calcpow(number, power) multiplies number by itself power times in a loop, and returns the result. The caller stores it: answer = calcpow(base, expo). So calcpow(2, 5) returns 32.

Functions come in four combinations: with or without arguments, and with or without a return value.

Flow of execution: Python runs statements from top to bottom. When it reads a def, it remembers the function but does not run its body. Only at a call does control jump into the function; when the function ends, control comes back to the statement after the call. A function must be defined before it is called; otherwise Python raises a NameError (Program 7-11).

A function can return several values at once. They are returned as a tuple: return (area, perimeter), and received like this: area, perimeter = calcAreaPeri(l, b).

A function can also call another function. In Program 7-13, trafficLight() calls light() to decide which message to show.

return gives a value back; no return gives None.
return gives a value back to the caller.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.