Search code examples
pythonpython-2.7loopsfor-loopcontinue

How to use "continue" in single line if esle within a for loop


I have a for loop and within that there is a simple single line if condition. I want to use continue option in the else part.

This does not work :

def defA() : 
    return "yes"
flag = False
for x in range(4) : 
    value = defA() if flag else continue
                              ^
SyntaxError: invalid syntax

Working code :

for x in range(4) : 
    if flag : 
        defA()
    else : 
        continue

Solution

  • There is no such thing as a single line if condition in Python. What you have in your first example is a ternary expression.

    You are trying to assign continue to a variable named value, which does not make any sense, hence the syntax error.