Learn / Beginner / Lesson 11

Functions

13 min Tested on Python 3.15Updated By
In short

A function is a named, reusable block of code. You define it with def name(parameters):, send results back with return, and call it with name(arguments). Functions keep code short, testable and easy to change, and type hints like def area(w: float, h: float) -> float: document what goes in and out.

Defining and calling

Python
def greet(name: str) -> str:
    """Return a friendly greeting."""
    return f"Hello, {name}!"

message = greet("Asha")
print(message)
print(greet("Ben"))
Output
Hello, Asha!
Hello, Ben!
  • def starts the definition; the indented block is the body.
  • return sends a value back. Without it, a function returns None.
  • The text in triple quotes is a docstring — editors and AI tools show it as help.
  • Type hints (name: str, -> str) don't change how code runs, but they make it clearer and let tools catch mistakes.

Default values and keyword arguments

Python
def price_with_vat(amount: float, rate: float = 0.21) -> float:
    return round(amount * (1 + rate), 2)

print(price_with_vat(100))
print(price_with_vat(100, 0.06))
print(price_with_vat(rate=0.09, amount=50))
Output
121.0
106.0
54.5

Parameters with defaults are optional. Naming arguments when you call (rate=0.09) makes calls self-explanatory and lets you pass them in any order.

Returning several values

Python
def stats(numbers: list[float]) -> tuple[float, float, float]:
    return min(numbers), max(numbers), sum(numbers) / len(numbers)

low, high, mean = stats([4, 8, 15, 16, 23, 42])
print(low, high, mean)
Output
4 42 18.0

Any number of arguments

Python
def total(*numbers: float) -> float:
    return sum(numbers)

def profile(**details: str) -> None:
    for key, value in details.items():
        print(f"{key} = {value}")

print(total(1, 2, 3, 4))
profile(name="Ana", city="Ghent")
Output
10
name = Ana
city = Ghent

*args collects extra positional arguments into a tuple; **kwargs collects extra named arguments into a dictionary.

Scope: variables inside functions

Python
count = 10

def demo():
    count = 99      # a new local variable
    return count

print(demo())
print(count)
Output
99
10

Variables created inside a function exist only there. Pass values in as parameters and send results out with return — avoid changing global variables.

The mutable default trap

Python
def add_item(item, basket=[]):      # bug!
    basket.append(item)
    return basket

print(add_item("apple"))
print(add_item("pear"))

def add_item_fixed(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

print(add_item_fixed("apple"))
print(add_item_fixed("pear"))
Output
['apple']
['apple', 'pear']
['apple']
['pear']

Practice

Write a function to_fahrenheit(celsius: float) -> float that returns celsius * 9 / 5 + 32. Then print the result for 0, 37 and -40, one per line.

Expected output:
32.0
98.6
-40.0
Your code

Quick check

1. What does a function return if it has no return statement?

2. Do type hints make Python check types when the code runs?

3. Why is def f(items=[]): a problem?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →