1

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
Selcuk
  • 45,843
  • 11
  • 87
  • 90
Azee77
  • 48
  • 5
  • `X if C else Y` is an expression. `continue` is a statements. Expressions in Python cannot contain statements. Transform your `if` expression into an `if` statement to fix. – Amadan Aug 30 '19 at 03:52
  • Ternary operator allow you to assign a variable to A if match condition else B. That's mean B should be a variable or value instead of a Python keyword (`continue`). – Toan Quoc Ho Aug 30 '19 at 03:52

3 Answers3

5

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.

Selcuk
  • 45,843
  • 11
  • 87
  • 90
1

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
exan
  • 1,275
  • 2
  • 11
  • 24
  • True, but it is safe to assume that this is an excerpt from the actual code, therefore we don't know if there are more lines after the `if` clause within the `for` loop. – Selcuk Aug 30 '19 at 04:29
  • Agree, hence I first suggested him to explain the problem first rather discussing his solution. Just a suggestion though! – exan Aug 30 '19 at 04:38
-1

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

gahooa
  • 114,573
  • 12
  • 89
  • 95
  • This is not exactly correct, nor answers the question. You can write, for example `if flag: foo()`. Note the lack of indentation in the control structure. – Selcuk Aug 30 '19 at 03:55
  • 1
    @Selcuk your answer was undoubtedly better, but my answer is still literally accurate. Python does use indent for control structures - and - what he wanted to do is not possible in Python. I did not intend to convey that there is no possible way to skip an indent occasionally like my favorite `if DE:BUG(...)` statement :) – gahooa Aug 30 '19 at 15:48