What”s the scope of a variable initialized in an if statement?

StackOverflow

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 created in a module global/available to the entire module?

Answer rating: 376

Python variables are scoped to the innermost function, class, or module in which they"re assigned. Control blocks like if and while blocks don"t count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can"t stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)





Get Solution for free from DataCamp guru