python - Variables defined inside if or for statements -
what happens variables assigned first time (defined) inside if
statement or for
loop if long time passed when code run. there sort of garbage collection may result in not defined variable exception. example:
if true: a=1 else: a=3 # long time passed , other codes run # . # . # . print (a)
i encountered error in code suspect reason. documented somewhere in official python documentation ?
in python, if define variable within if
statement, continue exist after if
statement concludes. scopes defined class
, def
, or global scope; if you're in function , define variable inside if
, example, variable exist until function done executing.
be careful, however, of defining variables in code this:
if x == true: = 1 else: print "not true"
if have code this, , x
ends being false
, a
not defined. later calls a
throw exception result. make sure rid of potential problems of sort.
Comments
Post a Comment