Functions: Write Code Once, Use It Many Times
Package steps into your own functions: def, parameters and arguments, return values, the difference between print and return, default values, keyword arguments and docstrings. Then watch a function call step by step.
Why functions?
A function is a named, reusable piece of code. You already use functions others wrote: print, len, round. Writing your own means you write a calculation once, give it a good name, and then use it anywhere with one line.
Think of a function like a recipe card: "Pancakes: takes flour, eggs and milk, gives back pancakes". The card has a name, the inputs it needs, the steps, and the result it hands back. Functions make programs shorter, easier to read, easier to test, and easier to fix: fix the function once and every use is fixed.
Defining and calling a function
defdefines the function. This only creates it: the body does not run yet.nameis a parameter: a placeholder for the input.- Calling the function,
greet("Sita"), runs the body withnameset to "Sita". The value you pass in, "Sita", is called the argument. returnends the function and sends a value back to wherever it was called.
def area(width, height):
return width * height
print(area(3, 4)) # 12
room = area(5.5, 4)
print("room:", room, "m²")
def to_fahrenheit(celsius):
return celsius * 9 / 5 + 32
for c in [0, 20, 37, 100]:
print(c, "°C =", to_fahrenheit(c), "°F")Watch the code run: calling a function
Watch each call get its own private variables, which disappear when the call ends.
Interactive: this part runs in your browser.
return versus print
This is the most important beginner distinction about functions:
printshows a value on the screen, for a human to read. The rest of the program cannot use it.returngives the value back to the code that called the function, so it can be stored, added up, tested or passed on.
A function without a return gives back None. Most useful functions return their result and leave printing to the caller.
def add_print(a, b):
print(a + b) # shows it, returns None
def add_return(a, b):
return a + b # gives it back
x = add_print(2, 3) # prints 5
y = add_return(2, 3) # prints nothing
print("x is", x) # None: there was nothing to keep
print("y is", y) # 5
print(add_return(2, 3) * 10) # a returned value can be used in more mathsSeveral parameters, defaults and keywords
- Arguments are matched to parameters by position: first to first, second to second.
- A parameter can have a default value, used when the caller leaves it out:
def price(amount, tax=0.1):. Parameters with defaults go after those without. - Callers can name the arguments,
price(100, tax=0.15). These keyword arguments make calls easier to read and can be given in any order.
def total_price(amount, tax=0.10, discount=0.0):
after_discount = amount * (1 - discount)
return round(after_discount * (1 + tax), 2)
print(total_price(100)) # default tax, no discount: 110.0
print(total_price(100, 0.15)) # by position: tax = 0.15
print(total_price(100, discount=0.2)) # by keyword: skip tax, set discount
print(total_price(discount=0.5, amount=80)) # keywords in any orderReturning several values
A function can return several values separated by commas. They come back as a tuple, which you can unpack into separate names.
def stats(numbers):
lowest = min(numbers)
highest = max(numbers)
average = sum(numbers) / len(numbers)
return lowest, highest, average
lo, hi, avg = stats([12, 7, 19, 3, 9])
print(f"min {lo}, max {hi}, average {avg:.1f}")Docstrings: explain your function
A docstring is a string on the first line of the function body that says what it does, what it needs and what it returns. Editors show it when you hover over the function, and help(function) prints it. Good names plus a short docstring make your code readable months later.
def bmi(weight_kg, height_m):
"""Return the body mass index: weight divided by height squared, rounded to 1 decimal."""
return round(weight_kg / height_m ** 2, 1)
print(bmi(70, 1.75))
help(bmi)Functions calling functions
Small functions can be combined into bigger ones. This is how real programs are built: each function does one clear job, and a higher-level function uses them in order.
def clean(name):
"""Strip spaces and fix capitals."""
return name.strip().title()
def initials(name):
"""'sita gurung' -> 'S.G.'"""
return ".".join(word[0] for word in clean(name).split()) + "."
def badge(name, role="Student"):
return f"{clean(name)} ({initials(name)}) – {role}"
print(badge(" sita GURUNG "))
print(badge("leo walker", role="Tutor"))Code example: functions and dictionaries
A worked example: read it step by step (every part is explained), then run it and experiment.
Interactive: this part runs in your browser.
Practice: check yourself
Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.
Write a function area(width, height) that returns width × height.
Write greet(name, greeting="Hello") that returns "Hello, Sita!" for greet("Sita") and "Hi, Leo!" for greet("Leo", "Hi").
Write summary(numbers) that returns three values: the smallest, the largest and the average (rounded to 1 decimal). For [4, 8, 15, 16, 23, 42] it returns (4, 42, 18.0).
Summary
Define a function with def name(parameters): and an indented body; call it with name(arguments). Use return to hand back a result (print only shows it). Defaults make parameters optional, keyword arguments make calls clear, and a docstring explains the function.
Key words
- function
- a named, reusable block of code
- define
- create a function with
def(the body does not run yet) - call
- run a function:
area(3, 4) - parameter
- a name in the definition that receives an input
- argument
- the actual value passed in a call
- return value
- the result a function gives back with
return - default value
- a value a parameter takes if the caller leaves it out
- docstring
- a description string at the start of a function
Common mistakes
- Defining a function but never calling it, then wondering why nothing happens.
- Using
printinstead ofreturn, then gettingNonewhen you try to use the result. - Forgetting the brackets:
areaon its own is the function itself;area(3, 4)calls it. - Code after
returnin the same block never runs. - Calling with the wrong number of arguments: TypeError: missing 1 required positional argument.
- Putting a parameter without a default after one with a default: SyntaxError.
Quiz
1. A function has no return statement. What does calling it give back?
2. What does a function without a return statement give back?
3. In def area(w, h): and the call area(3, 4), what are 3 and 4?
4. def f(x): print(x * 2). What is y after y = f(5)?
5. With def total(amount, tax=0.1), which call is valid?
6. When does the body of a function run?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- The Python Tutorial: More Control Flow Tools ↗ if, for, range, functions, arguments and lambdas, from python.org
- Think Python, 3rd edition (Allen Downey) ↗ free online textbook that teaches thinking like a programmer