Posted By: Anonymous
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?
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]
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"
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 >>> a 0 >>> i=101 >>> a = 1 if i<100 else 2 if i>100 else 0 >>> a 2 >>> i=99 >>> a = 1 if i<100 else 2 if i>100 else 0 >>> a 1