After this lesson you can write your own function with def, call it whenever you need it, and spot the places in your programs where a function would save you from copying code.
Why functions exist
Imagine a small shop that prints a banner at the top of every report. Without functions you would paste the same few print lines into each report, and when the shop changes its name you would have to find every copy. A function gives a block of code a name so you can write it once and use it many times.
You have already used functions. print() and len() are built into Python. Now you will make your own.
Defining and calling a function
You define a function with the keyword def, then a name, parentheses and a colon. The indented lines below it are the body.
def show_banner():
print("=" * 20)
print(" Corner Shop Report")
print("=" * 20)
show_banner()====================
Corner Shop Report
====================Read the sequence carefully. The def block only creates the function. Nothing printed while Python read it. The output appears at the last line, show_banner(), which is a call. The parentheses are what make it a call.
You can call it as many times as you like:
show_banner()
print("Sales: 42 items")
show_banner()====================
Corner Shop Report
====================
Sales: 42 items
====================
Corner Shop Report
====================Defining does not run
A common surprise for beginners is that a definition by itself does nothing visible. You can prove it:
def say_hello():
print("hello from inside the function")
print("before the call")
say_hello()
print("after the call")before the call
hello from inside the function
after the callThe message from inside the function appears between the other two lines, at the moment of the call and not where the def is written.
Function names
Function names follow the same rules as variable names: letters, digits and underscores, not starting with a digit. By convention they are lowercase words joined by underscores, such as show_banner or print_receipt. Choose a name that says what the function does, usually starting with a verb. A name like f1 tells the next reader nothing, including you in two weeks.
Docstrings
If the first line in the body is a string, Python treats it as the function's docstring: a short description. Tools and the built-in help() function read it.
def print_receipt_header():
"""Print the standard header used on every receipt."""
print("Corner Shop")
print("Thank you for your visit")
print_receipt_header()
print(print_receipt_header.__doc__)Corner Shop
Thank you for your visit
Print the standard header used on every receipt.Keep a docstring to one clear sentence when the function is simple.
Functions calling functions
A function body can call other functions. This is how bigger programs are built from small pieces.
def line():
print("-" * 20)
def print_footer():
line()
print("Open daily 9 to 6")
line()
print_footer()--------------------
Open daily 9 to 6
--------------------Python does not care in which order the two definitions appear, as long as both exist before print_footer() is called.
A function is an object
The name of a function is an ordinary name pointing at a function object. That is why print_footer without parentheses does not run anything, it only refers to the function.
print(type(print_footer))
copy = print_footer
copy()<class 'function'>
--------------------
Open daily 9 to 6
--------------------Here copy is a second name for the same function, so calling copy() does exactly the same job. You will use this idea later when you pass functions to other functions.
Choosing what goes into a function
A useful rule is that a function should do one job, and its name should describe that job. If you struggle to name it without using the word "and", it probably does two jobs and should be split. Small functions are easier to test, easier to reuse and easier to read, because the main part of a program then reads almost like a list of steps.
def print_title():
print("DAILY SALES")
def print_rows():
print("tea x3")
print("milk x2")
def print_report():
print_title()
print_rows()
print_report()DAILY SALES
tea x3
milk x2Here print_report is short enough to understand at a glance, and each helper can be changed without touching the others. When you read a large program, you often only need to read the top-level function and trust the names below it.
Common mistakes
- Forgetting the parentheses. Writing
show_banneron its own line does nothing. You must writeshow_banner()to run it. - Calling before defining. Python reads the file from top to bottom, so the
defmust run before the call. - Forgetting to indent the body. Every line of the body needs the same indentation, usually four spaces.
- Forgetting the colon at the end of the
defline. - Copy and paste instead of a function. If you find yourself pasting the same lines a third time, stop and make a function.
Here is what calling a function before it is defined looks like:
announce()
def announce():
print("open")NameError: name 'announce' is not definedThe first line fails because announce does not exist yet at that moment.
Exercise
Write a function called print_label that prints a line of 15 dashes, the text Fresh Bakery, and another line of 15 dashes. Call it twice. Then add a docstring.
Show one possible answer
def print_label():
"""Print the bakery label."""
print("-" * 15)
print("Fresh Bakery")
print("-" * 15)
print_label()
print_label()---------------
Fresh Bakery
---------------
---------------
Fresh Bakery
---------------The next lesson shows how to hand values into a function and get answers back out. A video version of this topic is in the video course at /learn/python/.
Key points
- A function is a named block of code. Define it once with def, then run it any time by writing its name followed by parentheses.
- Defining a function does not run it. The body only runs when you call the function.
- The body must be indented, and a docstring on the first line describes what the function does.
- Functions remove repetition, so a change is made in one place instead of many.
- You already use functions such as print() and len(). Writing your own works the same way.