Functions are useful for gathering similar pieces of code in one place. Consider the following mathematical function:
The Python equivalent is as follows:
def f(x): return 2*x + 1
In Figure 1.5, the elements of a function block are explained:
- The keyword def tells Python we are defining a function.
- f is the name of the function.
- x is the argument or input of the function.
- What is after return is called the output of the function.
Figure 1.5: Anatomy of a function
Once the function is defined, it can be called using the following code:
f(2) # 5
f(1) # 3