Python - What is the output: nonlocal variable?

Question

What is the output of the following code?

def func(): 
   X = 'test' 
   def nested(): 
       nonlocal X 
       X = 'Test' 
   nested() 
   print(X) 

func() 


Click to view the answer

Test

Note

The nonlocal statement means that the assignment to X inside the nested function changes X in the enclosing function's local scope.

Without this statement, this assignment would classify X as local to the nested function, making it a different variable.

The code would then print 'test' instead.

Related Quiz