user11173832
user11173832

Reputation:

cannot assign to conditional expression

if i+1 < stages[i]: tried[i] = (tried[i] + 1) if tried[i] != None else tried[i] = 0

if i+1 < stages[i]: tried[i] = (tried[i] + 1) if tried[i] != None else tried[i] = 0 ^ SyntaxError: can't assign to conditional expression

I got an error of cannot assign to conditional expression. Not sure which part I did wrong.

Upvotes: 1

Views: 3939

Answers (2)

Jon
Jon

Reputation: 11

The overall structure you're looking for, since you are trying to accomplish an assignment with multiple conditional expressions, is this: variable = expression condition else expression condition ... else expression. You can even use parentheses to remind yourself of how it will be parsed: variable = (expression condition else expression condition ... else expression). The total conditional expression must end with "else".

For instance, I have the following code:

x = 5
if x == 1:
    a = '1'
elif x == 2:
    a = '2'
else:
    a = '3'
print(a)

Using a conditional expression, it becomes:

x = 5
a = '1' if x == 1 else '2' if x == 2 else '3'
print(a)

I'm not sure what your assignment and conditional expressions

if i+1 < stages[i]: tried[i] = (tried[i] + 1) if tried[i] != None else tried[i] = 0

would look like when expanded, as some information is missing:

missing_expression = '?'
if i+1 < stages[i]:
    tried[i] = (tried[i] + 1)
elif tried[i] != None:
    tried[i] = missing_expression
else:
    tried[i] = 0

When the missing expression is supplied, your conditional expression should look like:

tried[i] = (tried[i] + 1) if i+1 < stages[i] else missing_expression if tried[i] != None else 0

Upvotes: 1

norok2
norok2

Reputation: 26886

Should be:

if i+1 < stages[i]: tried[i] = (tried[i] + 1) if tried[i] != None else 0

without the last triend[i] = 0, just 0 (also triend would be probably wrong anyway).

Upvotes: 4

Related Questions