Chapter 1: Introduction

Returning a function

face Josiah Wang

You can also return a function.

Remember, you are returning a function (func), not the output of a function call (func())!

Make sure you understand how x and n are used in the example below!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def power(n):
    def nth_power(x):
        return x ** n

    return nth_power

squarer = power(2) # returns the nth_power function
print(squarer(5)) # 25 (5**2)

cuber = power(3)
print(cuber(4)) # 64 (4**3)

Line 7 calls the function power() with argument n=2. This function returns its inner function nth_power (but does not call this function). Lines 2 and 3 are part of a function definition, so are not yet executed since the function has not been called.

The variable squarer points to the nth_power function that was returned by power(2), so calling squarer() is equivalent to calling nth_power(). So Line 8 calls nth_power() with the argument x=5. Since n has been set to 2 earlier, the function will compute 5**2, and return 25.

The same goes for Lines 10-11.

Make sure you understand everything we have discussed so far before moving on. Otherwise it will get really confusing!