Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 319
froadie Avatar asked May 13 '10 19:05

froadie


People also ask

What is the scope of an if statement?

if is a conditional statement, which returns true or false based on the condition that is passed in it's expression. By default, if-statement is implemented on only one line, that follows it. But if we put block after the if-statement, it will be implemented on the whole block.

Can we initialize a variable in if condition?

C++17 If statement with initializer Now it is possible to provide initial condition within if statement itself. This new syntax is called "if statement with initializer".

Can you assign a variable in an if statement?

Yes, you can assign the value of variable inside if.

What is the scope of this variable?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.


1 Answers

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.)

like image 61
Luke Maurer Avatar answered Sep 23 '22 00:09

Luke Maurer