Functions
Everything about functions
- The basics: elements necessary for function definition, often essential.
- Types: optional annotations but useful for improving code readability and maintenance.
- Docstrings: integrated documentation that explains the role of a function.
- Assertions: tools for making functions more robust by imposing constraints.
The basics: arguments, parameters, return value
Definition
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.
Example
# 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
Types
Definition
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.
Example
# 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
Definition
Assertions allow verifying that function arguments or results respect certain conditions. They are useful for detecting errors during development.
Example
# 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
The docstring
Definition
A docstring is a string placed directly after a function definition. It documents its role, arguments, and return value.
Example
# 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))