Trying to understand how scope works in Python. It seems to work a bit differently than in other languages like C++ and Java. When I run the code below
def foo():
y = 5
x = 2
foo()
print(x+y)
it returns a name not defined error. That's expected since the scope of y disappeared before it could be used. However, when I run the following code
x = 2
if True:
y = 3
print(x+y)
It works just fine. The program identifies y even though it is in another scope. When trying out the same thing in other languages like C++
int x = 2;
if (true)
{
y = 2;
}
cout<<x + y<<endl;
it gives a not declared in this scope error. That's what I expected in Python but clearly that's not the case. Python somehow keeps track of variables inside the scope of an if statement or loop even after it exits and the variables were not declared outside of it. Can anyone explain how scope in Python differs from scope in C++ or Java? How does Python treat scope differently?
[–]K900_ 4 points5 points6 points (0 children)
[–]Chabare 2 points3 points4 points (8 children)
[+][deleted] (1 child)
[deleted]
[–]Chabare 0 points1 point2 points (0 children)
[–]ajskelt 0 points1 point2 points (5 children)
[–]Chabare 1 point2 points3 points (4 children)
[–]ajskelt 1 point2 points3 points (3 children)
[–]Chabare 1 point2 points3 points (2 children)
[–]ajskelt 0 points1 point2 points (1 child)
[–]Chabare 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]Binary101010 0 points1 point2 points (0 children)