7

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
alvas
  • 115,346
  • 109
  • 446
  • 738

1 Answers1

15

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343