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.return still returns something: None. That is why b in the second editor is None.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
- Run the first editor. The same
areafunction answers three different questions, andgreetshows a default argument being used and then overridden. - Run the second editor. Both functions put 10 on the screen, but
a is 10whileb is None. - Watch it fail. The last line adds 1 to
aand works. Change it tob + 1and run: TypeError, because you cannot add a number to None. - Fix it. Add a
returntodoubled_printand 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.