A function is a block of code that performs a specific task. It can receive arguments (the data passed to the function) and use parameters (the names of variables used inside the function to designate these arguments). A function can also return a return value using the return keyword.
# Definition of a function that adds two numbers
def addition(a, b):
return a + b
# Function call
result = addition(3, 5)
print(result) # Displays: 8
The parameters and return value of a function can be of different types: integer, float, string, boolean, list, etc. You can use type annotations to indicate expected types.
Good to know: type annotations are not binding. They only serve to document the code and help static analysis tools.
# Function that concatenates two strings
def concatenate(string1: str, string2: str) -> str:
return string1 + string2
# Function call
result = concatenate("Hello, ", "world!")
print(result) # Displays: Hello, world!
Assertions allow verifying that function arguments or results respect certain conditions. They are useful for detecting errors during development.
# Function that divides two numbers
def division(a: float, b: float) -> float:
assert b != 0, "The denominator cannot be zero."
return a / b
# Function call
result = division(10, 2)
print(result) # Displays: 5.0
A docstring is a string placed directly after a function definition. It documents its role, arguments, and return value.
# Function that calculates the area of a circle
import math
def circle_area(radius: float) -> float:
"""
Calculates the area of a circle from its radius.
Arguments:
- radius (float): the radius of the circle, must be positive.
Returns:
- float: the area of the circle.
"""
assert radius > 0, "The radius must be positive."
return math.pi * radius ** 2
# Function call
print(circle_area(5))