Quarry School

Return a result — quick review

In plain words

A shop has a price board on the wall and a clerk with a calculator.

Rule

A return line works out its expression, ends the call and gives that value back to the calling line; a return with no expression gives back None. A call whose body runs to its end without reaching a return line gives back None, and that includes a body that prints its result.

Step

  1. Decide what value the rest of the program needs from the function.

  2. Write return followed by that value, or by the expression that works it out, at each point where the function's work is done. In the first worked example that is the last line of the body.

  3. At the call, do something with the value: give it a name, print it or use it in an expression.

  4. Trace a call by replacing it with the value it returns, then finishing the line the call was in.

  5. If a function should only display something, leave return out and call it on a line of its own.

Trap

Printing inside a function is not returning. A function whose body prints its result and has no return line gives back None. A line such as total = show_double(5) + 1 then displays 10 and stops with a TypeError when Python tries to add None and 1. A TypeError is the error for an operation applied to a value of the wrong type. Use return when the calling line needs the value.

The opposite slip is to return a value and drop it. A line that holds only total_price(4, 3) runs the function, and in a file that is run it displays nothing. Python writes out the value of such a line only when the line is typed in the Shell and the value is not None.