-1

Just started learning python and came across this

def f(g):
    return g(2)

def square(x):
    return x ** 2

print(f(square)) # which gives 4

How does inputting square into the f function equate to 4?

martineau
  • 112,593
  • 23
  • 157
  • 280
zko
  • 1

3 Answers3

3

When you call a function, the value of the argument is assigned to the named parameter. The call

print(f(square))

can be thought of as "expanding" to

g = square
print(g(2))
chepner
  • 446,329
  • 63
  • 468
  • 610
0

Calling f(square) is square(2) which is 2**2 so 4

rapaterno
  • 496
  • 3
  • 6
0

In python functions are first-class values, considered objects as anything else, hence you can pass them as parameters to another function.

In your case, you are "composing" f with g, which in turn has an invocation with fixed 2 inside f. In this sense, f is a function whose purpose is to feed 2 into another function, given as argument.

Knowing that g squares a number, it's easy to see how g(2) is 4, then f(g) will return 4.

rikyeah
  • 1,542
  • 2
  • 9
  • 20