def h(y):
x = x + 1
x = 5
h(x)
print(x)
So this is from the MIT 6.00.1 course. This bit of code throws an UnboundedLocalError: local variable 'x' referenced before assignment.
I even tried doing this like this:
x = 5
def h(y):
x = x + 1
h(x)
print(x)
But that also gives the UnboundLocalError
. My thought process was that declaring x = 5
before the function is created and placed into the global stack (sorry if the lingo is wrong) would ensure that when we call h(x)
the globally scoped variable x
would have a value to pass to the function.
I'm also curious that this somewhat similar snippet of code does NOT produce the UnboundLocalError
:
x = 12
def g(x):
x = x + 1
return x
g(x)
And I am running these code snippets through Python Tutor, I (am fairly sure) that I generally understand the order in which things are occurring as the code executes.
Sorry, and thanks in advance - I am looking to understand what's really going on here instead of glossing over it. I realize that usually locally scoped variables are less confusing and less likely to cause weird bugs.