When you find yourself copying the same lines again and again, a function can help. A function gives a group of steps a name.
Defining a function
def greet(name):
print("Hello,", name)
print("Welcome to the quest!")
The def line gives the function a name and lists what information it needs. The indented lines are what it does.
Calling it
To use it, write its name with a value inside parentheses: greet("Pip"). You can call it as many times as you like with different values.
Parameters and return values
A parameter is information passed in, like name. A function can also send a value back with return, which lets you use the result somewhere else:
def double(number):
return number * 2
Why functions help
- You write the steps once and reuse them.
- Fixing a bug in one place fixes it everywhere.
- Good names make a program read like a story.
Common mistakes
- Defining a function but forgetting to call it.
- Forgetting that variables created inside a function are not visible outside it.
- Printing a value when you meant to return it.
A project idea
Make a small set of functions for a quiz game: one to ask a question, one to check the answer, and one to show the score.
Takeaway
Functions let you build bigger programs from small, named pieces.
Continue with the book
Explore the full treatment, worked examples, and exercises in Code Quest with Python.
Adapted from Code Quest with Python, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
