Kodiak North
Kodiak North

Reputation: 81

Ternary using pass keyword python

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

Answers (3)

Moinuddin Quadri
Moinuddin Quadri

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

Israel Unterman
Israel Unterman

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

Scott Hunter
Scott Hunter

Reputation: 49813

Ternary expression are used to compute values; neither pass nor continue are values.

Upvotes: 2

Related Questions