Functions
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
def greet(name: str) -> str:
"""Return a friendly greeting."""
return f"Hello, {name}!"
message = greet("Asha")
print(message)
print(greet("Ben"))Hello, Asha! Hello, Ben!
defstarts the definition; the indented block is the body.returnsends a value back. Without it, a function returnsNone.- 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
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))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
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)4 42 18.0
Any number of arguments
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")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
count = 10
def demo():
count = 99 # a new local variable
return count
print(demo())
print(count)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
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"))['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.
32.0 98.6 -40.0