Python functions: stop copy-pasting the same damn code
Updated · every example run on Python 3.9 to 3.15
Sooner or later you write the same four lines in three places. Then you find a bug in them, fix it in two places, and the third copy sits there for a month, quietly being wrong as hell. A function ends that: you write the lines once, give them a name, and use the name wherever you need them.
You have been calling functions since lesson 1. print, len, type and sorted are all functions somebody else wrote. Today you write your own, and they get to be just as useful and slightly more broken.
Define a function with def
def, a name, parentheses, a colon, and an indented body. It is the same colon-and-indent deal as if and for.
def say_hi():
print("Hi!")
print("Did you drink any water today?")
print("Before")
say_hi()
say_hi()
print("After")Before
Hi!
Did you drink any water today?
Hi!
Did you drink any water today?
AfterLook at the order of the output. Defining a function runs none of its body: Python just files the body away under the name say_hi. The body runs each time you call the name with parentheses, which is why "Hi!" shows up twice and only after "Before". Forget the parentheses, write say_hi on its own, and nothing happens at all: you mentioned the function without asking it to do anything, like reading a recipe out loud and expecting soup.
Parameters: give it something to work with
A function that does the exact same thing every time is a bit limited. Put names in the parentheses and the caller fills them in:
def feed(cat, grams):
print(f"{cat} gets {grams} g of food.")
print(f"{cat} acts like it's the first meal in weeks.")
feed("Biscuit", 40)
feed("Mr. Whiskers", 55)Biscuit gets 40 g of food.
Biscuit acts like it's the first meal in weeks.
Mr. Whiskers gets 55 g of food.
Mr. Whiskers acts like it's the first meal in weeks.cat and grams are parameters: placeholders in the definition. "Biscuit" and 40 are arguments: the real values in one call. They are matched by position, first to first, second to second, so feed(40, "Biscuit") would cheerfully announce that "40 gets Biscuit g of food."
Get the count wrong and Python refuses before running a single line of the body. One argument short is TypeError: missing 1 required positional argument; one too many is "takes 2 positional arguments but 3 were given".
return: hand a value back
print shows a value to you. return hands a value to the code that called the function, so it can store it, add it up or pass it on. The call itself turns into that value.
def add_tip(bill, percent):
tip = bill * percent / 100
return bill + tip
dinner = add_tip(80, 15)
print(dinner)
print(add_tip(20, 10) + add_tip(30, 10))
def grade(score):
if score >= 90:
return "A"
if score >= 75:
return "B"
return "C, and we don't talk about it"
print(grade(95))
print(grade(80))
print(grade(12))92.0
55.0
A
B
C, and we don't talk about itreturn also ends the function on the spot. In grade, a score of 95 returns "A" from the first if, and the lines below it never run. That is why there is no else anywhere: once a return fires, there is nothing left to be "else" about.
Returning None by accident
Here is the classic. A function that prints its answer instead of returning it:
def shout(text):
print(text.upper() + "!")
result = shout("pizza is here")
print(result)
print(result.upper())PIZZA IS HERE!
None
Traceback (most recent call last):
File "/home/me/project/main.py", line 6, in <module>
print(result.upper())
^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'upper'| Python | Prints |
|---|---|
| 3.9–3.15 | AttributeError: 'NoneType' object has no attribute 'upper' |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
The shouting appears, so everything looks fine. It fucking isn't. A function with no return returns None, so result is None, and the last line asks None for an .upper() it doesn't have. That is AttributeError: 'NoneType' object has no attribute, and the same mistake with square brackets gives TypeError: 'NoneType' object is not subscriptable. The fix is one word, return:
def shout(text):
return text.upper() + "!"
It is also why groceries = groceries.sort() from the lists lesson leaves you holding None: .sort() sorts the list in place and returns None, like any function with nothing to return. When a value comes back None and you don't know why, the first suspect is a function that forgot to return.
Default values and keyword arguments
Give a parameter a default with =, and the caller can leave it out. Name a parameter in the call, and the order stops mattering:
def order_coffee(size="medium", sugar=0, milk="none"):
print(f"A {size} coffee, {sugar} sugar, milk: {milk}")
order_coffee()
order_coffee("large")
order_coffee("small", 2)
order_coffee(milk="oat")
order_coffee(sugar=3, size="large")A medium coffee, 0 sugar, milk: none
A large coffee, 0 sugar, milk: none
A small coffee, 2 sugar, milk: none
A medium coffee, 0 sugar, milk: oat
A large coffee, 3 sugar, milk: nonemilk="oat" is a keyword argument: it skips straight past size and sugar, which keep their defaults. You have used these since lesson 1, by the way: sep="/" and end="" in print are keyword arguments.
Two rules keep Python from getting confused. In the definition, parameters without a default come first, so def order(size="medium", name): is a SyntaxError. In the call, positional arguments come first, so order_coffee(size="large", 2) is one too.
Local and global variables
A variable you create inside a function is local: it exists only while that call runs, and the rest of the program never sees it. A variable created at the top of the file is global, and a function can read it. Changing it is where the fun starts.
balance = 100
def show_balance():
print(f"Balance: {balance}")
def reset():
balance = 0
print(f"Inside reset: {balance}")
show_balance()
reset()
show_balance()
def spend(amount):
balance = balance - amount
return balance
spend(30)Balance: 100
Inside reset: 0
Balance: 100
Traceback (most recent call last):
File "/home/me/project/main.py", line 18, in <module>
spend(30)
~~~~~^^^^
File "/home/me/project/main.py", line 15, in spend
balance = balance - amount
^^^^^^^
UnboundLocalError: cannot access local variable 'balance' where it is not associated with a value| Python | Prints |
|---|---|
| 3.9–3.10 | UnboundLocalError: local variable 'balance' referenced before assignment |
| 3.11–3.15 | UnboundLocalError: cannot access local variable 'balance' where it is not associated with a value |
Run on CPython 3.9.6, 3.10.22, 3.11.17, 3.12.15, 3.13.17, 3.14.9 and 3.15.1, on November 11, 2026.
reset did not reset shit. balance = 0 inside a function makes a brand-new local balance that dies when the function ends, and the global one stays at 100.
spend is worse. Because it assigns to balance somewhere in its body, Python treats balance as local for the whole function, so the right-hand side reads a local that has no value yet. Python 3.9 and 3.10 call that "local variable 'balance' referenced before assignment"; from 3.11 on it is "cannot access local variable 'balance' where it is not associated with a value". Same crime, longer sentence. The page on UnboundLocalError has the details.
The fix is to pass the value in and return the new one, so the change happens where everyone can see it:
def spend(balance, amount):
return balance - amount
balance = spend(balance, 30)
There is also a global balance statement that lets a function change the global directly. It works, and it turns your program into a place where any function can move money behind your back. Pass and return.
Try it yourself
Write a function split_bill(total, people, tip=10) that adds a tip, as a percent of the total, and returns what each person pays. split_bill(90, 3) should give 33.0, and split_bill(90, 3, tip=20) should give 36.0.
Show the answer
def split_bill(total, people, tip=10):
with_tip = total + total * tip / 100
return with_tip / people
print(split_bill(90, 3))
print(split_bill(90, 3, tip=20))
It returns, it doesn't print, so the caller decides what to do with the number.
Questions
What is the difference between return and print in Python?
print writes a value to the terminal for a human to read, and the program can't use what it printed. return gives the value back to the code that called the function, where it can be stored in a variable or used in a calculation.
What does a Python function return if there is no return statement?
None. The same goes for a bare return with nothing after it, and for a function whose return sits in an if that didn't run.
What is the difference between a parameter and an argument?
A parameter is the name in the def line, such as grams. An argument is the value you pass in a call, such as 40. People mix the two words up constantly, and Python doesn't mind.
Can a Python function return more than one value?
Yes: return low, high hands back both, packed together as a tuple (like a list that can't be changed, which the dictionaries lesson introduces properly), and low, high = price_range() unpacks them into two variables, the same way for i, item in enumerate(...) did in the loops lesson.
Sources
- Defining functions, Python documentation
- Default argument values, Python documentation
- Keyword arguments, Python documentation
- The return statement, Python documentation
- Naming and binding, Python documentation
Read on November 11, 2026.