Functions¶
Basic function definitions¶
The basic syntax for a Python function definition is
def function_name(param1, param2):
body
As with control streams, Python uses indentation to separate the function from the function definition. The following simple example inserts the code into a function so that you can call it to get the factorial of a number:
1 def fact(n):
2 """Return the factorial of the given number."""
3 f = 1
4 while n > 0:
5 f = f * n
6 n = n - 1
7 return f
- Line 2
This is an optional documentation string, or
docstring
. You can get its value by callingfact.__doc__
. The purpose of docstrings is to describe the behaviour of a function and the parameters it takes, while comments are to document internal information about how the code works. Docstrings are Strings that immediately follow the first line of a function definition and are usually enclosed in triple quotes to allow for multi-line descriptions. For multi-line documentation strings, it is common to give a summary of the function on the first line, follow this summary with an empty line and end with the rest of the information.See also
- Line 7
The value is returned after the function is called. You can also write functions that have no return statement and return None, and when
return arg
is executed, the valuearg
is returned.
Although all Python functions return values, it is up to you how the return value of a function is used:
1 >>> fact(3)
2 6
3 >>> x = fact(3)
4 >>> x
5 6
- Line 1
The return value is not linked to a variable.
- Line 2
The value of the
fact()
function is only output in the interpreter.- Line 3
The return value is linked to the variable
x
.
Inspired by Mypy, so-called type
hints were introduced in Python, with which the types for parameters and return values can be defined, in our fact()
example with:
def fact(n: int) -> int:
...
or:
def factlist(flist: list[float]) -> list[float]:
...
We receive the types with the __annotations__
attribute at runtime:
>>> fact.__annotations__
{'n': <class 'int'>, 'return': <class 'int'>}
>>> factlist.__annotations__
{'list': list[float], 'return': list[float]}
However, there is no type check at runtime.
See also