Question

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
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top