Menu

Sub Programs

Functions and return values

A function is a sub program that returns a value to the code that called it. That value is called the return value, and the keyword that sends it back is return.

When Python reaches a return statement, the function stops straight away, so code later in that call is not run. If the return is inside an if branch, reaching it ends the function early; if that branch is not taken, the rest of the function can still run.

Using what comes back

The call itself produces the returned value, so you can use it just like a value you typed yourself. For example, a call that returns 4 can be stored in a variable, used in a calculation, printed as part of output, or joined to text with str().

If you call a function and do nothing with the result, the value is lost as soon as the line finishes. Nothing is displayed automatically, so a call on its own produces no output and leaves you nothing to use later.

True or false functions in conditions

A function can return True or False as well as a number. Since the call is already that Boolean value, you can put it straight into an if condition without comparing it to anything. Comparing the call with True as well works, but the comparison is unnecessary because the call already gives the condition.

def fillBowls(water_left):
    full_bowls = water_left // 7
    return full_bowls

water = 30
bowls = fillBowls(water)
print("Bowls filled:", bowls)
print("Water left over:", water % 7)

Output:

Bowls filled: 4
Water left over: 2

Here the value from return is caught by bowls and printed. You could put the call directly in the first print line instead of storing it first; the output would be the same, because the call itself is the value.

The main program calls fillBowls(water), passing 30 to water_left, and the function returns 4, which bowls catches. The output is Bowls filled: 4 and Water left over: 2.

Practise this