I wrote this code in Python as I was trying to understand the global statement -
eggs=24
def f():
print(eggs)
eggs=25
print(eggs)
f()
print(eggs)
The output should be
24
25
24
Python should see eggs = 24
as a global variable and when the function f()
is called, it should print eggs=24
as the local value is not assigned to eggs till now. Then a local value of 25 should be assigned to eggs
and 25 should be printed on the screen after 24. After the function returns, eggs
should be assigned it’s global value that is 24 and 24 should be printed on the screen at last.
But I got an error message saying that “UnboundLocalError: local variable 'eggs' referenced before assignment
”.
Where am I wrong in understanding of how Python runs this function?