-2

Consider the following code:

if b > 5:
    a += 1
elif b < 0:
    a += 2
else:
    a += 3

In C there is a convenient (although not very transparent) way to write it in one line:

b > 5 ? a+=1 : b < 0 ? a+=2 : a+=3;

Is there a way to write it that concisely in Python?

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Mikhail Genkin
  • 3,000
  • 4
  • 23
  • 45
  • 2
    The concise way would be to write it as a full if statement. I would hate to have to read a nested conditional. – Andrew Li Aug 24 '18 at 11:47
  • based on "The Zen of Python, by Tim Peters", "Simple is better than complex.". read it by `import this` in python – U3.1415926 Aug 24 '18 at 12:05

1 Answers1

4

there is, but it's not all that much shorter and loses on readability:

a += 1 if b>5 else 2 if b<0 else 3

Zinki
  • 445
  • 4
  • 10