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 function is a named block of code that performs a specific task and can be called from other parts of the program.

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 accept parameters — values that are passed to the function when it's called:

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

# Calling the function with an argument
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:

Python 3.13
# Function with an arbitrary number of positional arguments
def make_pizza(*toppings):
    print("Making a pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")

make_pizza("pepperoni")
Making a pizza with the following toppings:
- pepperoni
make_pizza("mushrooms", "green peppers", "extra cheese")
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
# Function with 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'}

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)