This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Higher-order functions

Remember higher-order functions? We discussed these in Functional Programming.

Recall that higher-order functions are functions that take a function as an input argument or return a function. For example, the Python map() and filter() functions are higher-order functions that takes functions as input.

Since all functions are objects in Python, we can pass them into a function as input arguments. What is the output for the following piece of code?

def laugh():
    print("MUAHAHAHAHA!! :D")

def cry():
    print("WAAA!! TT_TT")      

def multiplier(func, repeats):
    for i in range(repeats):
        func()

multiplier(laugh, 5)
multiplier(cry, 2)

You can also return a function. Remember, you’re 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!

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)

Make sure you understand everything on this page before moving on. Otherwise it will get really confusing!