Hey everyone,
I’m new to Python and I’m getting a bit confused about namespaces and scopes. Can someone help me understand why the following code throws an UnboundLocalError?
x = 1
def foo():
x = x + 1
print(x)
foo()
When the interpreter processes the line x = x + 1, shouldn’t it do something like this:
- Look at the right side of the
=: find the namexin the global namespace (which is 1), and get the result 1+1=2. - Create a new object (
<int>2). - Create the name
xin the local namespace. - Bind the local name
xto the object<int>2(the assignment).
In C++, similar code would work just fine and output the expected result. Here’s how that looks:
#include <iostream>
int x = 1;
void foo()
{
x = x + 1;
std::cout << x;
}
int main()
{
foo();
return 0;
}
I see there are some differences between how Python and C++ handle variables. Anyway, any insights you can offer would be super helpful!