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

Question:

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
Asked By: Azee77

||

Answers:

Python uses indent for control structures. What you want to do is not possible in python.

Answered By: gahooa

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.

Answered By: Selcuk

Can you kindly explain a bit as what you are trying to achieve may be experts can suggest you a better alternative. To me it doesn’t make sense to add else here because you are only adding else to continue-on, which will happen in anycase after the if condition.

In any case, if I get it right, what you are looking for is a list comprehension. Here is a working example of how to use it,

def defA() :
    return "yes"

flag = True

value = [defA() if flag else 'No' for x in range(4)]  #If you need to use else
value = [defA() for x in range(4) if flag]            #If there is no need for else
Answered By: exan

Yes you can you continue statment in a single line as shown below. Let me know if you face some issue

for i in range(1, 5):
    if i == 2: continue
    print(i)
Answered By: Gaurav Pandey
for x in range(4) : 
    if not flag: continue
    defA()

That’s how I would do it. I like this guard-clause style pattern so the reader knows if there’s no flag, there’s other logic to worry about below and it avoids the extra indent.

Answered By: punkrockpolly