-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
  • 119,623
  • 25
  • 170
  • 301
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
  • 497,756
  • 71
  • 530
  • 681
0

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

rapaterno
  • 626
  • 4
  • 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,896
  • 4
  • 11
  • 21