Sub topic 1
Defining and calling your first function
A function is a named block of code that you can run as many times as you like. You have already called built-in functions such as print and len. This chapter shows how to write your own with def, what Python does when it reads a definition, and what happens when you call the function. It also covers the errors you are most likely to meet first.
Prerequisites
This chapter assumes you can do the following:
- Use variables and basic data types: numbers, strings and booleans.
- Work with lists, tuples and dictionaries at a basic level.
- Call built-in functions such as
printandlen. - Write an
ifstatement and a basic expression.
You do not need to know anything about parameters, return or scope beyond what this chapter introduces. Later chapters cover those topics in depth.
Why write functions
Functions give you three things:
- Reuse. You write the logic once and call it from many places.
- Naming. A good name such as
averagetells the reader what a block of code does, so they don't have to read it. - Isolation. Variables created inside a function stay inside it, which keeps unrelated parts of a program from interfering with each other.
The anatomy of a definition
Here is a complete function, followed by a call to it:
def greet(name):
return f"Hello, {name}!"
message = greet("Ada")
print(message) # Hello, Ada!The definition has these parts:
- The keyword
defstarts the definition. greetis the function's name. It follows the same rules as a variable name, and Python style (PEP 8) prefers lowercase words joined by underscores.(name)is the parameter list. A parameter is a variable that receives a value each time the function is called.- The colon ends the header line.
- The indented lines below the header are the body. Python uses indentation to decide where the body ends, and the standard is four spaces per level.
The call is greet("Ada"). The value "Ada" is an argument. A parameter is the name in the definition. An argument is the value you supply in the call. The next chapter treats this difference in detail.
What Python does with a def statement
def is an executable statement, not a declaration. When Python reaches it, it does two things:
- It creates a function object from the body. The body is compiled but not run.
- It binds the name
greetto that object, in the same wayx = 5bindsxto an integer.
This explains several behaviors that surprise newcomers.
The body does not run at definition time
Defining a function runs none of its code. A print inside the body produces no output until you call the function.
A function must be defined before the call executes
Python runs a module from top to bottom. A call that executes before the def statement has run fails:
try:
hello()
except NameError as error:
print(error) # name 'hello' is not defined
def hello():
print("hello")
hello() # helloThe order that matters is the order of execution, not the order of the text. A function body can refer to a function that is defined later in the file, because the name is looked up only when the call happens:
def first():
return second()
def second():
return "ok"
print(first()) # okBoth definitions have run by the time first() is called, so the lookup of second succeeds.
Functions are objects
Because a function is bound to a name like any other value, you can inspect it, give it a second name, or pass it around:
def greet(name):
return f"Hello, {name}!"
print(type(greet)) # <class 'function'>
print(greet.__name__) # greet
alias = greet
print(alias("Grace")) # Hello, Grace!The name alias refers to the same function object as greet. No copy is made. Passing functions as arguments is a technique you will meet later. For now, note that the name and the function are separate things.
Redefinition replaces the old function
Since def binds a name, running a second def with the same name rebinds it. Python gives no warning:
def status():
return "first"
def status():
return "second"
print(status()) # secondAccidental duplicate names are a common source of confusing bugs in longer files. Linters such as Ruff and Flake8 report them.
Calling a function
A call has the function's name followed by parentheses. The parentheses are what trigger execution. The name alone just refers to the function object:
def greet(name):
return f"Hello, {name}!"
print(greet) # <function greet at 0x...>
print(greet("Ada")) # Hello, Ada!The address in the first line differs from run to run. If you see output like that where you expected a result, you probably left out the parentheses.
When Python executes a call, it follows these steps:
- It evaluates the arguments.
- It binds each argument to the matching parameter, inside a new local namespace for this call.
- It runs the body until a
returnstatement executes or the body ends. - It evaluates the call expression to the returned value.
The sequence diagram shows this exchange for greet("Ada").
Because a call is an expression, you can use it anywhere a value is allowed:
def greet(name):
return f"Hello, {name}!"
print(len(greet("Ada"))) # 11
if greet("Ada").startswith("Hello"):
print("polite") # politeFunctions with no parameters
A function does not need any parameters. The parentheses stay in both the definition and the call:
def separator():
return "-" * 20
print(separator()) # --------------------The body cannot be empty
Python requires at least one statement in a body. While you are sketching a program, use pass, which does nothing, or a docstring, which Python accepts as a statement:
def load_config():
pass
def save_config():
"""Not implemented yet."""
print(load_config()) # NoneCalling a stub is safe, and the call evaluates to None. A later chapter explains why. A bare def load_config(): with nothing under it is a SyntaxError, or an IndentationError if the next line is not indented.
Common first errors
The errors below cover most of what goes wrong with a first function.
| Symptom | Likely cause | Fix |
|---|---|---|
| `SyntaxError: expected ':'` | The colon is missing from the `def` line | Add `:` at the end of the header |
| `IndentationError: expected an indented block` | The body is not indented, or is empty | Indent the body by four spaces, or use `pass` |
| `NameError: name 'f' is not defined` | The call ran before the `def`, or the name is misspelled | Move the call below the definition, or fix the spelling |
| `TypeError: greet() missing 1 required positional argument: 'name'` | The call supplied fewer arguments than the function needs | Pass every required argument |
| `TypeError: greet() takes 1 positional argument but 2 were given` | The call supplied more arguments than the function accepts | Remove the extra argument |
| Output shows `<function greet at 0x...>` | The call has no parentheses | Write `greet(...)` |
The two TypeError cases are easy to reproduce:
def greet(name):
return f"Hello, {name}!"
for call_args in [(), ("Ada", "Grace")]:
try:
greet(*call_args)
except TypeError as error:
print(error)
# greet() missing 1 required positional argument: 'name'
# greet() takes 1 positional argument but 2 were givenPython checks the number of arguments before it runs any of the body. A call with the wrong count never starts executing.
Choosing names and keeping functions small
A function is easier to test and reuse when it does one job and has a name that says what the job is. Python convention suggests these habits:
- Use a verb phrase for an action, such as
load_configorsend_email. Use a noun or a question for a function that computes a value, such asaverageoris_valid. - Avoid names that shadow built-ins. A function called
listormaxhides the built-in of the same name for the rest of the module. - If you cannot name a function without writing "and" in the name, it probably does two jobs and should be split.
A complete example
This short program defines two small functions and calls them in a loop:
def format_price(amount):
return f"${amount:,.2f}"
def describe(item, amount):
return f"{item}: {format_price(amount)}"
for item, amount in [("Laptop", 1299.5), ("Mouse", 24)]:
print(describe(item, amount))
# Laptop: $1,299.50
# Mouse: $24.00Notice that describe calls format_price, and the loop calls describe. Each function is small enough to read in one glance, and each can be tested on its own.
Exercise
A script contains the lines print(double(4)) followed, further down, by def double(n): return n * 2. What happens when you run it, and what is the smallest change that fixes it?
Show answer
Python raises NameError: name 'double' is not defined. The print call executes before the def statement has run, so the name does not exist yet. Moving the def above the print call, so the function is defined before it is called, fixes it.
Exercise
What is the difference between greet and greet("Ada") in an expression, and which of them runs the function body?
Show answer
greet is the function object itself. Evaluating it does not run anything. greet("Ada") is a call. The parentheses make Python run the body with name bound to "Ada", and the expression evaluates to the returned value.