Lesson 21 of 30 · Functions
Defining Functions
Write your own Python functions with def. Understand defining versus calling, why functions make code reusable and the mistakes beginners make.
- 6 min read
- Beginner
- Reviewed
- What a function is and why programmers use them
- How to define a function with def
- The difference between defining a function and calling it
You have been using functions all along
print(), len(), input() and int() are all functions: named pieces of code that do one job. Someone wrote them once, and you use them without thinking about how they work inside.
Now you will write your own.
Why write functions?
Look at this program. The same three lines appear twice.
print("====================")
print(" Welcome, learner! ")
print("====================")
print("Some content here...")
print("====================")
print(" Welcome, learner! ")
print("====================")If you want to change the banner, you must change it in two places. In a real program it might be twenty places, and you would miss one. A function fixes this: write the code once, give it a name and use it as often as you like.
Defining a function
def show_banner():
print("====================")
print(" Welcome, learner! ")
print("====================")
show_banner()
print("Some content here...")
show_banner()The first four lines define the function:
- The keyword
def, short for "define". - The function's name, following the same rules as variable names.
- A pair of brackets, then a colon.
- An indented block: the code that runs when the function is used. This is called the function's body.
Defining is not running
This is the idea beginners most often miss. Defining a function only teaches Python what the name means. Nothing happens until you call it by writing its name followed by brackets.
def say_hello():
print("Hello!")
print("The function has been defined, but not called yet.")
say_hello()
say_hello()Remove the two say_hello() lines and run it again. The word Hello! never appears.
Define before you call
Python reads from top to bottom, so a function must be defined above the line that calls it.
greet()
def greet():
print("Hi there!")This raises NameError: name 'greet' is not defined, because Python reaches the call before it has seen the definition. Move the call below the function to fix it.
Functions can use everything you know
A function body can contain variables, loops, if statements and calls to other functions.
def print_multiples_of_three():
for number in range(1, 11):
if number % 3 == 0:
print(number, "is a multiple of 3")
def show_report():
print("Report starting")
print_multiples_of_three()
print("Report finished")
show_report()Naming functions well
A function does something, so give it a name that starts with a verb: show_banner, calculate_total, send_email. Use lowercase with underscores, as you do for variables.
A good first line inside a function is a short description in triple quotation marks. This is called a docstring, and tools can show it to anyone using your function.
def show_banner():
"""Print the welcome banner."""
print("=== Welcome ===")
show_banner()Common mistakes
Define a function named welcome and call it two times.
# 1. Define a function called welcome that prints: Welcome to Python! # 2. Call it twice, so the output is exactly two lines: # Welcome to Python! # Welcome to Python!
What happens when Python reads a def block?
Summary
- A function is a named block of code that does one job.
- Define it with
def name():and an indented body. - Call it with
name(). Nothing runs until you call it. - A function must be defined before the line that calls it.
- Functions let you write code once and reuse it.
Next: giving functions information to work with.
Finished reading? Tick it off to track your progress.