Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using continue in python ternary? [duplicate]

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
like image 897
alvas Avatar asked Jan 21 '14 11:01

alvas


People also ask

Can we use continue in ternary operator?

continue is a control structure statement, not an expression. And hence, it can't be an operand of the ternary operator.

How do you continue a ternary operator in Python?

You cannot; continue is a statement and the conditional expression is an expression, and you cannot use a statement inside an expression.

How do you break a ternary operator in multiple lines?

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.

Is ternary better than if-else?

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.


1 Answers

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
like image 101
Martijn Pieters Avatar answered Sep 23 '22 19:09

Martijn Pieters