I want to set a variable based on the value of another variable in python. But when I ask for the value of the variable set in the if
-then
statement, it can't find the variable, obviously because it is now out of scope.
Consider the following:
>>> a = True
>>> if a:
... b=1
... else:
... b=2
>>> print b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
Is there a pythonic way to write this? For example, the following code works, but is it "the right way" to write it, or is there a better way?
>>> b = None
>>> if a:
... b=1
... else:
... b=2
...
>>> b
1