Higher-Order Functions

Defintion of Higher-Order Functions:
a function that either:

  1. accepts a function as an argument, or
  2. returns a function
    (In Python, functions are also treated as objects)

function as argument

def loud(text):
    return text.upper()

def quiet(text):
    return text.lower()

def hello(func):
    text = func("Hello")
    print(text)

hello(loud)
hello(quiet)
Output:
HELLO
hello

return a function

def divisor(x):
    def dividend(y):
        return y / x
    return dividend

divide = divisor(2)  
# pass 2 to x and return function called, dividend() 

print(divide(10))    
# divide is a variable refered to function dividend()

print(divisor(2)(10))    
# The same output as the above.
Output:
5.0
5.0