What you'll learn
- Define a function with
def, give it a name, and call it - Explain the two reasons functions exist: to name an idea and to avoid repeating it
- Follow what happens when a function is called, line by line
- Write a docstring so the next reader knows what the function is for
Concept
A function is a named block of code you can run whenever you want by writing its name followed by parentheses. You have been calling functions since your first program: print("hi") runs the code inside print with "hi" as its input. Now you will write your own. def greet(): starts one, the indented block underneath is its body, and greet() runs that body.
Functions exist for two reasons, and both are about people rather than computers. The first is naming: calculate_tax(price) tells a reader what is happening without them reading how. The second is reuse: code that lives in a function is written once and called from many places, so a fix in one place fixes every use. Any time you catch yourself copying a block of code, that block wants to be a function.

Defining a function runs nothing. Python reads the def, remembers the body under the name, and moves on. Only a call executes the body, and when the body finishes, execution jumps back to the line after the call. This jump is worth tracing slowly once: the program does not go top to bottom any more, it goes where the calls send it and comes back.

Inside a function you can use return to hand a value back to the caller. def square(n): return n * n makes square(4) an expression worth 16, which you can print, store, or pass to another function. A function without a return still returns something: the special value None, which means "nothing". The next lesson goes deep on inputs and outputs; this one is about the shape.
The first line of a body can be a string in triple quotes: the docstring. It says what the function does, in one sentence, and help(your_function) shows it, exactly as it does for the built-ins. Write one for every function whose purpose is not clear from its name alone. Function names follow the same convention as variables, lowercase with underscores, and should be verbs or verb phrases: load_config, send_email, is_valid.
Code
Define, then call. The body runs once per call, and nothing is printed until the first call happens, even though the definition comes first.
# greet.py
def greet():
print("Hello from a function")
print("before any call")
greet()
greet()
print("after two calls")
before any call
Hello from a function
Hello from a function
after two callsA function with an input and a return. The result is a value you can use anywhere a value can go.
# square.py
def square(n):
return n * n
print(square(4))
result = square(9)
print(result + 1)
print(square(square(2)))
16
82
16Reuse in action. Three lines that were nearly identical become three calls, and the formatting rule lives in one place.
# receipt_lines.py
def line(name, price):
"""Return one receipt line with the price aligned to the right."""
return f"{name:<12}{price:>7.2f}"
print(line("coffee", 3.5))
print(line("bagel", 2.25))
print(line("juice", 4))
help(line)
coffee 3.50
bagel 2.25
juice 4.00
Help on function line in module __main__:
line(name, price)
Return one receipt line with the price aligned to the right.
A function with no return gives back None. Printing the result of such a call is the most common surprise in a first week of Python.
# none_return.py
def announce(text):
print(text.upper())
value = announce("shipping")
print(value)
SHIPPING
NoneTry it yourself
Create shapes.py with three functions: area_rectangle(width, height), area_circle(radius) using 3.14159, and describe(name, area) that returns a string like "circle: 78.54". Call them to print the descriptions of a 3 by 4 rectangle and a circle of radius 5. Add a docstring to each and check one with help.
Common mistakes
- Forgetting the parentheses on a call.
greeton its own names the function without running it;greet()runs it. - Defining a function after the line that calls it. Python must have read the
defbefore the call is reached; put definitions above their first use. - Printing inside a function when you meant to
return. A function that prints its answer cannot hand it to other code; return the value and let the caller decide whether to print.
What's next
defcreates a function without running it; calling it with()runs the body and comes back.- Functions exist to name an idea and to avoid repetition; copied code wants to become a function.
returnhands a value back, a function withoutreturngivesNone, and a docstring explains the purpose.
You can create your own tools. Next you will see exactly how data goes into a function and comes back out: parameters, arguments, defaults, and return values.