Why does this one line if else cause a syntax error? Can it be done with one line?

condition = True
result = 1
# this works
result += 1 if condition else result
print(result) # prints 2
# this does not work
result += 1 if condition else result -= 1
print(result) # SyntaxError: invalid syntax, for -=
condition = True
result = 1
result += (1 if condition else result)
print(result) # prints 2
result += (1 if condition else result -= 1)
print(result) # SyntaxError: invalid syntax, for -=

There is still the exact same error with the parentheses.

You asked why this line makes a syntax error. The ()s show you why. Everything to the right of += is taken as the expression to add to result.

1 Like

Sure, it could be done in one line, if you add a value that results in a decrease in the result by 1. The real problem is that you need to rewrite this line

because right now it doubles result if the condition is False.

The single line if statement is better though of as a strangely written ternary expression and should be used as such.

Ah, now I see what is going on. Refactored it and working:

condition = True
result = 1
result = result + 2 if condition else result + 0
print(result) # prints 3
result = result + 1 if condition else result - 1
print(result) # prints 4

Thank you!

I’m still not sure this does what you think it does. Try switching condition = False and see what happens.

Yeah, I just caught that thanks. I’m going to edit it.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.