Search code examples
python-3.xfunctionreturn-type

What does return function do in the functions below?


Can you please explain to me what the return functions for call and squared_call do?

def mult_by_five(x):
    return 5 * x

def call(fn, arg):
    """Call fn on arg"""
    return fn(arg)

def squared_call(fn, arg):
    """Call fn on the result of calling fn on arg"""
    return fn(fn(arg))

print(
    call(mult_by_five, 1),
    squared_call(mult_by_five, 1), 
    sep='\n', # '\n' is the newline character - it starts a new line
)

Solution

  • If you take a step back and substitute in different functions, this will make more sense.

    Instead of return fn(fn(n)), look at simpler examples.

    return int(n)
    

    This returns the result of int(n). n is passed to int, then whatever int returns is returned.

    return str(int(n))
    

    This returns the result of str(int(n)). n is passed to int, then whatever int returns is passed to str, then whatever str returns is returned.

    The difficult part in that example is that fn are functions that were passed in as arguments to call and squared_call.

    When you write call(mult_by_five, 1), the return line in call is equivalent to:

    return mult_by_five(1)
    

    When you write squared_call(mult_by_five, 1), the return line in squared_call is equivalent to:

    return mult_by_five(mult_by_five(1))