Writing your own functions
Course contents (15 lessons)
- Getting started
- Installing Python 3.13 and running your first script
- Variables and basic data types
- Text, numbers and user input
- Working with strings
- Numbers and arithmetic
- Input and output: talking to the user
- Making decisions and repeating work
- Making decisions with if, elif and else
- Loops: for, while, break and continue
- Collections of data
- Lists and tuples
- Dictionaries and sets
- Functions and modules
- Writing your own functions
- Modules, pip and virtual environments
- Files and errors
- Reading and writing files
- Errors and exceptions
- Final project: expense tracker
- Project: build the expense tracker, part 1
- Project: summaries, search and improvements
Why functions matter
When you copy and paste the same five lines in three places, you have a problem waiting to happen. The day you need to change them, you will change two places and forget the third. A function gives a block of code a name so you can write it once and use it everywhere.
Your first function
def calculate_total(unit_price, quantity, tax_rate=0.17):
"""Return the invoice total including tax."""
subtotal = unit_price * quantity
return round(subtotal * (1 + tax_rate), 2)
def format_invoice_line(name, unit_price, quantity):
total = calculate_total(unit_price, quantity)
return f"{name:<15} {quantity:>3} x {unit_price:>8.2f} = {total:>10.2f}"
print(format_invoice_line("Paper ream", 1250.5, 4))
print(format_invoice_line("Stapler", 480, 2))
print(calculate_total(100, 1, tax_rate=0))
Output:
Paper ream 4 x 1250.50 = 5852.34
Stapler 2 x 480.00 = 1123.20
100.0
The parts of a function
The word def starts the definition. Then comes the name, round brackets with the parameters (the inputs), and a colon. The indented lines are the body. A return statement sends a value back to whoever called the function. The text in triple quotes right after the first line is a docstring. It documents what the function does and shows up in help tools.
Defining a function does not run it. The code only runs when you call it, with the name and brackets, as in calculate_total(100, 1). The values you pass in are called arguments.
Default values and keyword arguments
A parameter with = in the definition has a default. In calculate_total, tax_rate is 0.17 unless you say otherwise. When you call a function you can pass arguments by position, or by name. Named arguments make calls easier to read: tax_rate=0 is clearer than a bare 0.
Parameters with defaults must come after those without. def f(a=1, b): is a syntax error.
print is not return
This confuses almost every beginner, and it confused me too. print shows something on the screen. return hands a value back to your code. If you only print inside the function, you cannot use the result.
def add_wrong(a, b):
print(a + b)
result = add_wrong(2, 3) # prints 5
print(result * 2) # TypeError: None * 2
A function without a return gives back None. Good functions usually return a value and leave the printing to the caller. That also makes them easy to reuse and test.
Returning more than one value
A function can return a tuple, and the caller can unpack it.
def min_and_max(numbers):
return min(numbers), max(numbers)
low, high = min_and_max([4, 9, 2, 7])
print(low, high) # 2 9
Scope: where variables live
A variable created inside a function exists only while the function runs. It is local. Code outside cannot see it.
def make_label():
label = "SALE"
return label
make_label()
print(label) # NameError: name 'label' is not defined
Functions can read variables defined outside them, but changing those is a bad habit. Pass values in as parameters and return results instead.
The mutable default trap
Never use an empty list or dictionary as a default value.
def add_task(task, tasks=[]): # bug
tasks.append(task)
return tasks
print(add_task("a")) # ['a']
print(add_task("b")) # ['a', 'b'] - surprise!
The default list is created once, when the function is defined, and shared by every call. The fix is to use None and create a fresh list inside:
def add_task(task, tasks=None):
if tasks is None:
tasks = []
tasks.append(task)
return tasks
Keeping functions small
A good function does one thing and has a name that says what. calculate_total is a good name. process is not. If you need the word "and" to describe what a function does, it is probably two functions. Short functions are easy to read, test and reuse.
Try it yourself
Write a function is_even(n) that returns True or False. Then write average(numbers) that returns the average of a list, or 0 if the list is empty. Finally write apply_discount(price, percent=10) and call it three ways: with one argument, with two, and with the keyword name. Print each result.
def calculate_total(unit_price, quantity, tax_rate=0.17):
"""Return the invoice total including tax."""
subtotal = unit_price * quantity
return round(subtotal * (1 + tax_rate), 2)
def format_invoice_line(name, unit_price, quantity):
total = calculate_total(unit_price, quantity)
return f"{name:<15} {quantity:>3} x {unit_price:>8.2f} = {total:>10.2f}"
print(format_invoice_line("Paper ream", 1250.5, 4))
print(format_invoice_line("Stapler", 480, 2))
print(calculate_total(100, 1, tax_rate=0))
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account