-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
  • 73,278
  • 37
  • 149
  • 186
djhaskin987
  • 9,741
  • 4
  • 50
  • 86
  • 3
    What do you mean? Your first example works fine in all versions of Python. –  Apr 13 '15 at 18:45
  • 1
    I agree with iCodez -- 'b' is defined in python2.7 when I try your example. – bmhkim Apr 13 '15 at 18:46
  • 2
    It really really really should work as you've written it. Scoping in Python is done on a function level, so b should be in scope. – DavidW Apr 13 '15 at 18:46
  • 1
    Could you show actual interpreter output, copy-pasted from an actual interpreter session? Your examples have visible inconsistencies with the actual way the Python interpreter requires you to provide input. – user2357112 Apr 13 '15 at 18:48
  • It was because I put it in wrong, that's why it didn't work. sorry guys :( – djhaskin987 Apr 13 '15 at 19:44
  • @djhaskin987 Check my answer for a simpler way of assigning like this. – Anshul Goyal Apr 14 '15 at 04:37

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
  • 73,278
  • 37
  • 149
  • 186
  • In my years of Python, I've never seen an concise assignment like this. Is this even in the documentation? Thanks for the eye opener. – Malik Brahimi Apr 13 '15 at 18:48
  • You can use that everywhere: assignments, comprehensions, function arguments... it's quite excellent. :) – TigerhawkT3 Apr 13 '15 at 18:49
  • 2
    @MalikBrahimi: [Here's the relevant documentation.](https://docs.python.org/2/reference/expressions.html#conditional-expressions) – user2357112 Apr 13 '15 at 18:50