Sub topic 1
Defining and calling your first function
Prerequisites
This chapter assumes you already know the following:
- Variables and basic data types: numbers, strings and booleans.
- Lists, tuples and dictionaries.
- How to call built-in functions such as
printandlen. ifstatements and basic expressions.
You do not need to have written your own function before.
What a function is
A function is a named block of code that you can run as often as you like. You write the block once and then call it by name. This removes repeated code and gives a piece of logic a name that says what it does.
You define a function with the def keyword. The line that starts with def is the header. It holds the function name, a pair of parentheses, and a colon. The indented lines below it are the body.
def greet(name):
return f"Hello, {name}!"
message = greet("Ada")
print(message) # Hello, Ada!This example has four parts:
deftells Python you are defining a function.greetis the function name. Use lowercase words joined by underscores, such asread_config.nameinside the parentheses is a parameter. It is a variable that receives a value each time the function is called.- The body is indented by four spaces. Python uses that indentation to decide where the function ends.
Defining is not calling
Running a def statement does not run the body. It creates a function object and binds it to the name greet. The body runs only when you call the function by writing the name followed by parentheses.
def say_ready():
print("Ready")
say_ready # no parentheses: refers to the function, prints nothing
say_ready() # with parentheses: runs the body and prints ReadyLeaving off the parentheses is a common mistake. The expression say_ready is a valid reference to the function, so Python raises no error. Nothing happens either.
A function must be defined before the line that calls it is executed. The following code fails because the call runs before the def statement has created the name.
print(double(4)) # NameError: name 'double' is not defined
def double(n):
return n * 2Following a call step by step
When you write greet("Ada"), Python does the following:
- It evaluates the argument
"Ada". - It binds the parameter
nameto that value inside the function. - It runs the body from top to bottom.
- At
return, it stops and hands the result back to the caller. - The call expression is replaced by that result, so
messagereceives"Hello, Ada!".
A function with no parameters
A function does not need parameters. It can also do work without handing a value back. Here is a function that takes nothing and prints a fixed banner.
def banner():
print("=" * 20)
print("Report")
print("=" * 20)
banner()
banner()Calling banner() twice prints the banner twice. This is the main benefit of a function: the logic exists once, and you can use it many times.
Calling a function from another function
A function body can call other functions, including ones you defined yourself. The called function only needs to exist by the time the outer function runs.
def shout(text):
return text.upper() + "!"
def welcome(name):
return shout("welcome, " + name)
print(welcome("Ada")) # WELCOME, ADA!Breaking a task into small functions like this keeps each one easy to read and test.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `NameError` on a function name | The call runs before the `def` statement, or the name is misspelled | Define the function first and check the spelling |
| `TypeError: ... missing 1 required positional argument` | The call passes fewer arguments than the function has parameters | Pass a value for each parameter |
| `IndentationError` | The body is not indented, or the indentation is inconsistent | Indent every body line by the same amount |
| Nothing happens | The call has no parentheses | Write `name()` |
Exercise
Write a function named square that takes one parameter n and returns n * n. Then call it with 7 and print the result. What is printed, and what happens if you write print(square) instead?
Show answer
The code is def square(n): followed by an indented return n * n, then print(square(7)), which prints 49. Writing print(square) has no parentheses, so it does not call the function. It prints the function object itself, something like <function square at 0x...>.