-5

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
Anshul Goyal
  • 61,070
  • 31
  • 133
  • 163
djhaskin987
  • 8,513
  • 1
  • 45
  • 81

1 Answers1

2

For a simple assignment, you could use python's equivalent of ternary operator :

>>> a = True
>>> b = 1 if a else 2
>>> b
1

Also, I can't reproduce your given example,

In [1]: a = True

In [2]: if a:
   ...:     b = 1
   ...: else:
   ...:     b = 2
   ...:     

In [3]: print b
1
Community
  • 1
  • 1
Anshul Goyal
  • 61,070
  • 31
  • 133
  • 163