Python Functions: Recipes, return vs print, and Why Global State Bites
Turn repeated Python code into reusable functions with def, understand why return is not print, and avoid the mutable-default-argument trap.
You'll learn how to define functions with def, why return hands values back while print just writes to the screen, and how local scope keeps variables from colliding. Assumes basic Python variables.
1. Packaging code into reusable recipes
A function is a named block of code you define once with def and call whenever you need it:
def add_tax(price, rate=0.2):
return price * (1 + rate)
total = add_tax(100)
print(total)120.0Here rate=0.2 is a default argument: if the caller skips rate, Python uses 0.2; if they pass add_tax(100, rate=0.1), Python uses 0.1.
2. return vs print(): the #1 beginner mix-up
print() only draws text on your terminal and gives back None. return hands the actual value back to whoever called the function so you can store it or do math with it:
def broken_double(n):
print(n * 2)
result = broken_double(5)
print("result is:", result)10
result is: NoneIf you try broken_double(5) + 1, Python crashes with TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'. Always return results from calculation functions, and let the caller decide whether to print() them.
Fix broken_double by replacing print(n * 2) with return n * 2, then print broken_double(5) + 1 to get 11.
3. Variables inside a function stay inside
Variables created inside a function are local—they are born when the function runs and vanish when it returns. That is a good thing: it means two functions can both use a variable named total without stepping on each other.
One famous Python trap: never use a mutable list or dict as a default argument (def add_item(x, items=[]):). Python creates that default list once when def is read, so every future call shares the same list! Use items=None and create if items is None: items = [] inside.
Common mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
Function returns None unexpectedly | Used print() instead of return (or forgot return) | Add return value |
TypeError: f() missing 1 required positional argument | Forgot to pass a required argument | Pass the argument or give it a default |
Default list items=[] leaks across calls | Mutable default is shared by all calls | Use items=None and set items = [] inside |
Practice
- What does a Python function return if execution reaches the end without a
returnstatement?
Answer: None.
What you learned
- Define reusable logic with
def name(params):and hand back results withreturn. print()displays text and returnsNone;returnsends a value back to the caller.- Never use
[]or{}as default parameter values—useNoneinstead.