Putting an if-elif-else statement on one line?

I have read the links below, but it doesn’t address my question.
Does Python have a ternary conditional operator? (the question is about condensing if-else statement to one line)

Is there an easier way of writing an if-elif-else statement so it fits on one line?
For example,

if expression1:
   statement1
elif expression2:
   statement2
else:
   statement3

Or a real-world example:

if i > 100:
    x = 2
elif i < 100:
    x = 1
else:
    x = 0

I just feel if the example above could be written the following way, it could look like more concise.

x=2 if i>100 elif i<100 1 else 0 [WRONG]

14 Answers
14

Leave a Comment