What's the scope of a Python variable declared in an if statement?
Posted
by froadie
on Stack Overflow
See other posts from Stack Overflow
or by froadie
Published on 2010-05-13T19:07:45Z
Indexed on
2010/05/13
19:14 UTC
Read the original article
Hit count: 222
I'm new to Python, so this is probably a simple scoping question. The following code in a Python file (module) is confusing me slightly:
if __name__ == '__main__':
x = 1
print x
In other languages I've worked in, this code would throw an exception, as the x
variable is local to the if
statement and should not exist outside of it. But this code executes, and prints 1. Can anyone explain this behavior? Are all variables declared in a module global/available to the entire module?
© Stack Overflow or respective owner