Reputation: 81
I have a working conditional statement:
if True:
pass
else:
continue
that I would like to turn it into a ternary expression:
pass if True else continue
However, Python does not allow this. Can anyone help?
Thanks!
Upvotes: 4
Views: 1165
Reputation: 48077
Point 1: Are your sure your condition is right? Because if True
will always be True
and code will never go to else
block.
Point 2: pass
and continue
are not expressions or values, but a action instead You can not use these is one line. Instead if you use, 3 if x else 4
<-- it will work
Upvotes: 1
Reputation: 13510
pass
and continue
are a statements, and cannot be used within ternary operator, since the operator expects expressions, not statements. Statements don't evaluate to values in Python.
Nevertheless, you can still shorten the condition you brought like this:
if False: continue
Upvotes: 3
Reputation: 49813
Ternary expression are used to compute values; neither pass
nor continue
are values.
Upvotes: 2