Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error with ternary operator [duplicate]

I'm new to Python and I'm trying to use ternary opertor which has this format (I think so)

value_true if <test> else value_false

Here's a snippet of code:

expanded = set()

while not someExpression:

    continue if currentState in expanded else expanded.push(currentState)

    # some code here

But Python doesn't like it and says:

SyntaxError: invalid syntax (pointed to if)

How to fix it?

like image 749
megas Avatar asked Apr 10 '26 19:04

megas


1 Answers

Ternary operation in python using for expression, not statements. Expression is something that has value.

Example:

result = foo() if condition else (2 + 4)
#        ^^^^^                   ^^^^^^^
#      expression               expression

For statements (code blocks such as continue, for, etc) use if:

if condition:
     ...do something...
else:
     ...do something else...

What you want to do:

expanded = set()

while not someExpression:
    if currentState not in expanded: # you use set, so this condition is not really need
         expanded.add(currentState)
         # some code here
like image 60
defuz Avatar answered Apr 12 '26 08:04

defuz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!