Functions as Parameters and Return Values
Explore how to treat functions as first-class objects in Python by passing them as parameters and returning them from other functions. Understand practical examples including unit conversions and custom sorting with key functions. Gain skills to implement flexible and reusable functional programming patterns in Python.
We'll cover the following...
Functions as parameters
Consider this function that converts inches to centimeters and prints the result. One inch is 2.54 cm, so the conversion is a simple multiplication.
Suppose we wanted to generalize this function so that it could convert between different units. There are various ways to do this, but one way would be to remove the explicit call to inch2cm from the convert function. Instead, we could pass the function as a parameter, as shown below:
Notice that the function is passed in as a normal parameter, f. When we need to call f to do the conversion, we just use f(x) exactly like any other function.
When we call convert, we need to pass inch2cm in as the first parameter. Instead of using inch2cm(), which would try to call the function, we use the syntax, inch2cm, to pass the ...