...

/

Functions as Parameters and Return Values

Functions as Parameters and Return Values

Learn how to use functions as parameters and as return values in Python.

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.

Press + to interact
def inch2cm(x):
return x*2.54
def convert(x):
y = inch2cm(x)
print(x, '=>', y)
convert(3) # 3 => 7.62

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:

Press + to interact
def inch2cm(x):
return x*2.54
def convert(f, x):
y = f(x)
print(x, '=>', y)
convert(inch2cm, 3) # 3 => 7.62

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 ...

Access this course and 1400+ top-rated courses and projects.