How can I use continue in python ternary? Is that even possible?
E.g.
>>> for i in range(10):
... x = i if i == 5 else continue
give a SyntaxError: invalid syntax
If continue in ternary is possible, is there any other way of doing this:
>>> for i in range(10):
... if i ==5:
... x = i #actually i need to run a function given some condition(s)
... else:
... continue
...
>>> x
5
continue is a control structure statement, not an expression. And hence, it can't be an operand of the ternary operator.
You cannot; continue is a statement and the conditional expression is an expression, and you cannot use a statement inside an expression.
Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion). Save this answer.
You cannot; continue
is a statement and the conditional expression is an expression, and you cannot use a statement inside an expression. After all, the continue
statement doesn't produce a value for the conditional expression to return.
Use an if
statement instead:
if i == 5:
x = i
else:
continue
or better:
if i != 5:
continue
x = i
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With