Function arguments
Functions accept arguments in different ways. In the simplest case, the arguments passed are assigned in the same order as the argument names in the signature:
def subtract(a, b):
return a - b
subtract(1, 2) # -1
However, the arguments can also be passed by name, so that the order is no longer taken into account, but only the names are relevant:
subtract(b=2, a=1) # -1
In addition, functions can define a default value that is used if the argument is not explicitly passed:
def subtract(a, b=0):
return a - b
subtract(1) # 1
If the number of arguments is not known, a special variable can be used to summarise all arguments not known by name in a tuple. This is achieved by placing an asterisk *
in front of the argument name:
def add(*args):
total = 0
for a in args:
total += a
return total
add(1, 2, 3) # 6
All explicitly named arguments can be summarised in a dictionary. A double asterisk **
is used for this purpose:
def collect_arguments(**kwargs):
return kwargs
collect_arguments(a=1, b=2) # {'a': 1, 'b': 2}
If you already have a tuple or a dictionary, these can also be converted into individual arguments using the same syntax:
def add(a, b):
return a + b
values = (1, 2)
add(*values) # 3
values = {'a': 1, 'b': 2}
add(**values) # 3
Type hints
In Python, the data types of variables are not strictly checked. In order to help other developers or yourself in the future to understand which arguments a function accepts and returns, type hints can be used. This is of course optional for your own code, but is used in the exercises to clarify what kind of arguments are expected. The data type is separated by a colon :
after the variable name in the function signature:
def add(a: int, b: int) -> int:
return a + b
This means that the function accepts two variables a
and b
as integers and returns an integer. If a list is to be passed instead, the following would be written:
def list_total(values: list[int]) -> int:
total = 0
for v in values:
total += v
return total
Here, the function accepts a list of integers and returns the sum as an integer. However, since you can also simply ignore the hints, it is also immediately clear that the function could also handle decimal numbers, even if the type hints do not say anything about this at first.