No, this is impossible (at least not with arbitrary statements), and this is not desirable. Placing everything on one line is likely to violate PEP-8 , which states that lines should not exceed 80 characters.
This is also against Zen Python: "Reading is calculated." (Type import this at the Python prompt to read all of this).
You can use ternary expression in Python, but only for expressions, not for operators:
>>> a = "Hello" if foo() else "Goodbye"
Edit:
Now your revised question shows that the three statements are identical except for the assigned value. In this case, the chain ternary operator really works, but I still think it is 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
Tim Pietzcker Dec 25 '12 at 9:16 2012-12-25 09:16
source share