What's the scope of a variable initialized in an if statement?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Island
--
Chapters
00:00 What'S The Scope Of A Variable Initialized In An If Statement?
00:41 Answer 1 Score 175
01:10 Answer 2 Score 49
01:51 Answer 3 Score 15
02:34 Accepted Answer Score 526
03:05 Thank you
--
Full question
https://stackoverflow.com/questions/2829...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #variables #ifstatement #scope #localvariables
#avk47
ACCEPTED ANSWER
Score 526
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.)
ANSWER 2
Score 175
Yes, they're in the same "local scope", and actually code like this is common in Python:
if condition:
x = 'something'
else:
x = 'something else'
use(x)
Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.
In other words, Python does not have block-level scopes. Be careful, though, with examples such as
if False:
x = 3
print(x)
which would clearly raise a NameError exception.
ANSWER 3
Score 49
Scope in python follows this order:
Search the local scope
Search the scope of any enclosing functions
Search the global scope
Search the built-ins
(source)
Notice that if and other looping/branching constructs are not listed - only classes, functions, and modules provide scope in Python, so anything declared in an if block has the same scope as anything decleared outside the block. Variables aren't checked at compile time, which is why other languages throw an exception. In python, so long as the variable exists at the time you require it, no exception will be thrown.
ANSWER 4
Score 15
As Eli said, Python doesn't require variable declaration. In C you would say:
int x;
if(something)
x = 1;
else
x = 2;
but in Python declaration is implicit, so when you assign to x it is automatically declared. It's because Python is dynamically typed - it wouldn't work in a statically typed language, because depending on the path used, a variable might be used without being declared. This would be caught at compile time in a statically typed language, but with a dynamically typed language it's allowed.
The only reason that a statically typed language is limited to having to declare variables outside of if statements in because of this problem. Embrace the dynamic!