Modules/Python/ Naming a Recipe

Functions and Return Values

Wrap a piece of work in a name, hand it inputs, get an answer back. The difference between printing and returning is the thing worth getting right.

Define once, call many times

def names the function, the parentheses list what it needs, and return hands a value back.


                        

Returning versus printing

One of these gives you a value you can use. The other just puts characters on the screen and hands back None.


                        

print is not return

return ends the function immediately and sends a value back to whoever called it.
A function with no return still returns something: None. That is why b in the second editor is None.
Printing shows a human the answer. Returning gives the program the answer. Only one of them can be added to, stored, or passed on.
A parameter can have a default - greeting="Hello" - which makes it optional at the call site.

Functions and Return Values: A Practical Guide

Inputs in, one answer out.

Quick Context

A function packages a piece of work under a name so you can run it again with different inputs. The names in the def line are parameters; the values you pass when calling are arguments. Everything inside is skipped until somebody calls it.

Why the distinction matters

A function that prints has already spent its answer - the value is gone the moment it hits the screen. A function that returns hands the value back, so it can be stored, added to, passed to another function, or printed later if you want. Almost every "why is my variable None?" question traces back to a function that printed where it should have returned.

Interactive Exploration Guide

  1. Run the first editor. The same area function answers three different questions, and greet shows a default argument being used and then overridden.
  2. Run the second editor. Both functions put 10 on the screen, but a is 10 while b is None.
  3. Watch it fail. The last line adds 1 to a and works. Change it to b + 1 and run: TypeError, because you cannot add a number to None.
  4. Fix it. Add a return to doubled_print and run again - the TypeError disappears.

Key Takeaway

def names a reusable piece of work; parameters describe what it needs and return hands an answer back. A function without a return gives you None, so printing inside a function is not a substitute for returning - only a returned value can be stored, combined or passed on.

Check yourself

0 of 3

Answer without scrolling back up.

  1. A function that prints but never returns gives its caller:

  2. In `def area(width, height):`, width and height are:

  3. What does `def greet(name, greeting="Hello")` let you do?

Cheat sheet

Functions and Return Values

Wrap a piece of work in a name, hand it inputs, get an answer back. The difference between printing and returning is the thing worth getting right.

PYTHON · vizlearn.in/python/functions_and_return.html