Functions in Python

When the same block of code is needed in several places in a program, you don't have to copy it: you can describe it once as a function and then call it by name. A function takes input values, does something with them, and usually returns a result.

What are functions?

A useful way to think about a function is as a "black box": you feed in arguments, something happens inside, and a result comes back out.

A function as a black box: arguments 5 and 3 enter the box def add(a, b): return a + b and 8 comes out

Creating and calling functions

Basic syntax

A function in Python is created using the keyword def:

Python 3.13
# Simple function example
def greet():
    print("Hello, world!")

# Function call
greet()
Hello, world!

Here def declares a function, greet is its name, the parentheses hold the parameters (none here), and after the colon comes the function body, indented.

Functions with parameters

Functions can take data from outside. The names you write in the parentheses when declaring the function are called parameters, and the concrete values you pass in when calling it are arguments. The function below has one parameter — name — and we call it twice with different arguments: "Anna" and "Peter".

Python 3.13
def greet(name):
    print(f"Hello, {name}!")

greet("Anna")
Hello, Anna!
greet("Peter")
Hello, Peter!

Return values

Functions can return the result of their work using the return operator:

Python 3.13
# A function with a return value
def add(a, b):
    return a + b

# Using the function's result
result = add(5, 3)
print(f"5 + 3 = {result}")
5 + 3 = 8

return immediately exits the function: any code after it won't run. This is handy when you want to bail out early in special cases:

Python 3.13
def describe(value):
    if value < 0:
        return "negative"
    return "non-negative"

print(describe(-5))
negative
print(describe(10))
non-negative

If a function has no return, it still returns a value: None. That's fine for functions that don't compute anything but do something (like printing to the screen):

Python 3.13
def say_hi():
    print("Hi!")

result = say_hi()
print(result)
Hi!
None

Function parameters

Positional and keyword arguments

Python supports two ways of passing arguments to a function:

Python 3.13
# A function with multiple parameters
def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type} named {pet_name}.")

# Positional arguments
describe_pet("dog", "Rex")
I have a dog named Rex.
# Keyword arguments
describe_pet(pet_name="Whiskers", animal_type="cat")
I have a cat named Whiskers.

Default parameter values

You can specify default values for parameters:

Python 3.13
# A function with a default parameter
def describe_pet(pet_name, animal_type="dog"):
    print(f"I have a {animal_type} named {pet_name}.")

# Using the default value
describe_pet("Rex")
I have a dog named Rex.
# Overriding the default
describe_pet("Whiskers", "cat")
I have a cat named Whiskers.

Arbitrary number of arguments

Sometimes you don't know in advance how many arguments will be passed. Special parameters handle this: a star before the name (*toppings) gathers all positional arguments together, and two stars (**user_info) gather all keyword ones.

Python 3.13
# An arbitrary number of positional arguments
def make_pizza(*toppings):
    print("Toppings:", toppings)

make_pizza("pepperoni")
Toppings: ('pepperoni',)
make_pizza("mushrooms", "green peppers", "extra cheese")
Toppings: ('mushrooms', 'green peppers', 'extra cheese')
# An arbitrary number of keyword arguments
def build_profile(**user_info):
    print(user_info)

build_profile(name="Anna", location="Moscow", field="programming")
{'name': 'Anna', 'location': 'Moscow', 'field': 'programming'}

Python gathers all the passed values into a single structure: positional ones into a group of values, keyword ones into name-value pairs. What these structures are and how to go through them one by one, we'll cover in the chapters on collections and loops.

Understanding check

Let's check how well you've absorbed the topic of functions:

What will the following code output?

Python 3.13
def mystery(x, y=2):
    return x * y

result = mystery(3)
print(result)

Practice tasks

Right below this article there's a block called Practice tasks. This is the first time you write a whole function: the def line with the name and parameters is already in the editor, and you fill in the body.

Where the values come from

The values the function works with arrive in its parameters. You don't need to invent or enter them: each test calls the function with its own values.

Anatomy of a test: its own parameter values, the function call and the expected result

A test tab shows everything at once: which values it passes in, how it calls the function, and what result it expects. Every test uses its own values, and all of them need to pass.

The result must be returned

The function must return its result with return. If you print it with print() instead, the test won't pass: the check looks at the returned value, not at what appeared on screen.