Azee77
Azee77

Reputation: 140

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

Upvotes: 6

Views: 6893

Answers (6)

Gerardo Olmos Ortiz
Gerardo Olmos Ortiz

Reputation: 1

This worked for me:

array = [1,2,3,4,5]
filtered_array = [x for x in array if x > 3]

Upvotes: 0

punkrockpolly
punkrockpolly

Reputation: 9908

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.

Upvotes: 2

Gaurav Pandey
Gaurav Pandey

Reputation: 21

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)

Upvotes: 2

exan
exan

Reputation: 3935

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

Upvotes: 1

Selcuk
Selcuk

Reputation: 59228

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.

Upvotes: 9

gahooa
gahooa

Reputation: 137322

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

Upvotes: 0

Related Questions