Timothy Kimman Timothy Kimman - 6 months ago 10
Python Question

Why is this output 30 in python?

Can someone explain why this code of python outputs 30? It seems like add = func ? But how does python knows this without declaring. It's a question in the python course from sololearn.com, a lot of people don't seem to understand

def add(x, y):
return x + y

def do_twice(func, x, y):
return func(func(x, y), func(x, y))

a = 5
b = 10

print(do_twice(add, a, b))

Answer
def do_twice(func, x, y):
    return func(func(x, y), func(x, y))

when called with add, 5 and 10 will return

add(add(5, 10), add(5, 10))

i.e.

add(15, 15)

which is indeed 30

add has been passed as the first parameter, so is called func inside do_twice. Likewise a is 5 and b is 10.

Comments