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

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


No, it's not possible (at least not with arbitrary statements), nor is it desirable. Fitting everything on one line would most likely violate PEP-8 where it is mandated that lines should not exceed 80 characters in length.

It's also against the Zen of Python: "Readability counts". (Type import this at the Python prompt to read the whole thing).

You can use a ternary expression in Python, but only for expressions, not for statements:

>>> a = "Hello" if foo() else "Goodbye"

Edit:

Your revised question now shows that the three statements are identical except for the value being assigned. In that case, a chained ternary operator does work, but I still think that it's less readable:

>>> i=100>>> a = 1 if i<100 else 2 if i>100 else 0>>> a0>>> i=101>>> a = 1 if i<100 else 2 if i>100 else 0>>> a2>>> i=99>>> a = 1 if i<100 else 2 if i>100 else 0>>> a1


If you only need different expressions for different cases then this may work for you:

expr1 if condition1 else expr2 if condition2 else expr

For example:

a = "neg" if b<0 else "pos" if b>0 else "zero"


Despite some other answers: YES it IS possible:

if expression1:   statement1elif expression2:   statement2else:   statement3

translates to the following one liner:

statement1 if expression1 else (statement2 if expression2 else statement3)

in fact you can nest those till infinity. Enjoy ;)