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
0

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.