01 def
A function is a named block of code you can run whenever you want. Defining one does not run it — you define it once and call it as often as you like.
The name follows the same rule as variables: snake_case, and it should be a verb, because a function does something.
first_function.py
# Define it
def greet():
print("Hello!")
# Nothing has printed yet. Now call it:
greet() # Hello!
greet() # Hello!
# The brackets are what calls it
greet # <function greet at 0x...> - the function itself
greet() # Hello! - running it
02 Arguments
A parameter is the name in the definition; an argument is the value you pass in. People use both words loosely and it rarely matters.
Order matters when you pass by position. Pass by name instead and order stops mattering, which makes a call with several arguments far easier to read.
arguments.py
def greet(name):
print(f"Hello, {name}!")
greet("Ada") # Hello, Ada!
greet() # TypeError: missing 1 required positional argument
# Several
def describe(name, room, days):
print(f"{name} lives in the {room}, watered every {days} days")
describe("fern", "kitchen", 7) # by position
describe(name="fern", room="kitchen", days=7) # by name, clearer
describe(days=7, name="fern", room="kitchen") # by name, any order
03 Default values
Give a parameter a default and it becomes optional. Parameters with defaults must come after those without.
Never use a list or a dictionary as a default. It is created once, when the function is defined, and every call shares the same one — so items pile up between calls. Use None and build the list inside.
defaults.py
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Ada") # Hello, Ada!
greet("Ada", "Welcome") # Welcome, Ada!
# The mutable default trap
def add_plant(name, plants=[]): # WRONG
plants.append(name)
return plants
add_plant("fern") # ["fern"]
add_plant("cactus") # ["fern", "cactus"] - the same list!
def add_plant(name, plants=None): # RIGHT
if plants is None:
plants = []
plants.append(name)
return plants
04 return is not print
print shows something to a human. return hands a value back to the code that called the function. They look similar in the terminal and are completely different.
A function with no return gives back None. So a function that prints and does not return looks right when you run it, and then gives you None the moment you try to use the answer.
return_vs_print.py
def double_print(n):
print(n * 2) # shows it
def double_return(n):
return n * 2 # hands it back
# In the terminal these look identical
double_print(5) # 10
print(double_return(5)) # 10
# But only one can be used
total = double_print(5) + 1 # TypeError: NoneType + int
total = double_return(5) + 1 # 11
# return also EXITS the function immediately
def check(n):
if n < 0:
return "negative" # stops here
return "positive or zero"
05 Returning more than one value
Separate values with commas and Python packs them into a tuple. Unpack them on the other side with the same number of names.
multiple_returns.py
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, mean = stats([4, 7, 2, 9])
print(low, high, mean) # 2 9 5.5
# Or keep the tuple whole
result = stats([4, 7, 2, 9])
result[0] # 2
# Returning a dictionary is clearer once there are more than three
def stats(numbers):
return {
"low": min(numbers),
"high": max(numbers),
"mean": sum(numbers) / len(numbers)
}
06 Local and global
A variable made inside a function exists only inside it. That is a feature: two functions can both use total without interfering.
A function can read a variable from outside, but assigning to that name makes a new local one instead of changing the outer value.
scope.py
def count():
n = 5 # local to count()
print(n)
count() # 5
print(n) # NameError: name 'n' is not defined
total = 0
def add():
print(total) # reading the outer one: fine
def broken():
total = total + 1 # UnboundLocalError
def fixed(current):
return current + 1 # pass it in, hand it back
total = fixed(total)
07 Mutable arguments
Passing a list does not copy it. The function gets the same list, so changing it inside changes it outside too.
Numbers, strings and booleans cannot be changed in place, so they are never affected this way. Lists, dictionaries and sets can be.
mutable_args.py
def add_item(items):
items.append("new") # changes the caller's list
plants = ["fern"]
add_item(plants)
print(plants) # ["fern", "new"]
# Copy first if you do not want that
def add_item_safely(items):
items = items[:] # or list(items)
items.append("new")
return items
# A number is never affected
def bump(n):
n = n + 1
count = 5
bump(count)
print(count) # still 5
08 Docstrings
A string on the first line of a function documents it. help(name) prints it, and editors show it when you hover over a call.
Write what it does and what it gives back, not how it works — the code already says how.
docstrings.py
def days_until_watering(last_watered, interval):
"""How many days until this plant needs water.
Returns a negative number if it is already overdue.
"""
return interval - days_since(last_watered)
help(days_until_watering)
09 One function, one job
The test: can you name it in a few words without using “and”? If not, it is doing two things and should be two functions.
Small functions are easier to name, easier to test, and reusable. A 60-line function with four jobs is used exactly once, by you, today.
one_job.py
# Doing three things
def process():
data = open("plants.txt").read()
rows = [line.split(",") for line in data.split("\n")]
for row in rows:
print(f"{row[0]}: {row[1]}")
# Three things, three functions
def read_file(path):
return open(path).read()
def parse_rows(text):
return [line.split(",") for line in text.split("\n")]
def show(rows):
for row in rows:
print(f"{row[0]}: {row[1]}")
show(parse_rows(read_file("plants.txt")))
10 Function mistakes to recognise
Six of these produce a wrong answer rather than a crash, which is what makes them worth learning to spot by eye.
Nothing on this page mentions that. Try a shorter word, or clear the filter.