What does the following code output? def outer(): x = 10 def inner(): nonlocal x x += 1 return x return inner f = outer() print(f(), f(), f())

Python Professional Hard

Python Professional — Hard

What does the following code output? def outer(): x = 10 def inner(): nonlocal x x += 1 return x return inner f = outer() print(f(), f(), f())

Key points

  • `nonlocal` keyword allows inner functions to modify variables from outer functions
  • Each call to `f()` increments the value of `x`
  • The output is 11, 12, 13
  • The function `inner` is returned by `outer` and stored in `f`

Ready to go further?

Related questions