0

Hello i am a bit confused; I am trying to write this logic in one liner but i can't get it right

if a < 0:
  a -= 1
else:
  a += 1

one liner:

a -= 1 if a <0 else a += 1
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
Ioan Kats
  • 523
  • 1
  • 7
  • 19
  • Does this answer your question? https://stackoverflow.com/questions/2802726/putting-a-simple-if-then-else-statement-on-one-line – Karl Olufsen Apr 30 '20 at 21:15

2 Answers2

2

The one line would look like this a -= 1 if a < 0 else -1 or a = a - 1 if a < 0 else a + 1 depending on your preference. This is because the a -= part is not changed by the if

2

Can do it using ternary operators:

a -= 1 if a < 0 else -1

However, ternary expressions are not very readable. Mostly useful with list comprehensions. Otherwise, they just complicate things.

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58