9.2 Functions in practice
In our study of functions, we started from arrows between sets and ended up with mental models such as formulas and graphs. For pure mathematical purposes, these models are perfectly enough to conduct thorough investigations. However, once we leave the realm of theory and start putting things into practice, we must think about how functions are represented in programming languages.
In Python, functions are defined using a straightforward syntax. For instance, this is how the square(x) = x2 function can be implemented.
def square(x):
return x**2
The result is an object of type function. (In Python, everything is an object.)
type(square)
function
Functions are called using the () operator.
square(12)
144
Python is well-known for its simplicity, and functions are no exception. However, this doesn’t mean that they are limited in features – quite the contrary: you can achieve a lot with the clever use of functions.