There is this code:
>>> if True:
... a = 4
...
>>> print a
4
Why variable a is still alive after if block? Shouldn’t it be destroyed when block if ends?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Python variables have scope inside a
function,classormodule. Variables initialised inifstatements,whilestatements andforstatements are available outside the if/while/for statement for useThis is different to many other languages where accessing the variable would throw an exception because of it being out of scope
Just to note, if the if/while/for statement is false and does not execute,
afor example would not be initialised and it would throw an error like so: