3

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?

0

1 Answer 1

12

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

8 Comments

break is not equivalent to continue at all
By the way, not x in y = x not in y.
I'm sorry my code misled you a little, I've edited code so you'll understand that I still need continue operator.
well if that's the case then print should not work in ternary operations.
@megas, Again, for expression: one if condition else two. For statements: if condition: do_something().
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.