0

I'm trying to simplify a chain comparison from 3 lines:

if -10 < amount < 10:  # amount can range from -999 to 999
    width = 3
else:
    width = 2

to a 1 line expression:

width = 3 if (-10 < amount < 10) else width = 2

Pycharm throws a SyntaxError

SyntaxError: can't assign to conditional expression

What would be to correct way to write simplify this statement? I tried:

width = 3 if (-10 < amount) else width = 2

but I receive the same error. I'm using Python 3. Thanks.

artomason
  • 3,625
  • 5
  • 20
  • 43
  • It is not a simplification but an attempt to make your code less readable. – Axalix Jan 06 '18 at 19:42
  • 1
    That depends on the surrounding code. A one-line if/else has the potential to make code more readable. At the very least, it makes it clear that the only purpose of that block is to conditionally assign a value to `width`. – Hans Musgrave Jan 06 '18 at 19:44
  • I'm aware of the readability factor which is why I'm only using this for a single variable, and added parentheses to make it a little easier on the eyes. I saw the error after I posted the question, perhaps it's time for some more coffee. Thank you for the help. – artomason Jan 06 '18 at 19:49
  • Possible duplicate of [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) – Georgy Jan 06 '18 at 20:00
  • 1
    @Georgy I felt that question didn't really answer whether or not a chain-comparision `(-10 < amount < 10)` vs `(-10 < amount)` was possible. My issue was that I was trying to redefine width a second time in the expression, which I blame on a lack of coffee. – artomason Jan 06 '18 at 20:09

1 Answers1

9

You want to write

width = 3 if (-10 < amount < 10) else 2

The entire right hand side has a value which is then assigned to width.

Hans Musgrave
  • 6,613
  • 1
  • 18
  • 37