"unresolved reference" in ternary if else one liner

Question:

I am trying to work out why the following line doesn’t work:

i = 0 if i // 3 == 0 else i += 1

I am getting an "unresolved reference ‘i’ " error despite the fact that i is defined before this line. Apologies if this is obvious but I am pretty new to ternaries and haven’t been able to find a good reason why this doesn’t work (although I suspect it may be something to do with the augmented assignment).

Thanks in advance.

Asked By: Adam Ladd

||

Answers:

You should change this to i = 0 if i // 3 == 0 else i + 1. The reason for this is that it parses as i = (0 if i // 3 == 0 else i + 1), not (i = 0) if (i // 3 == 0) else (i + 1) as you seem to assume.

Answered By: Code-Apprentice
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.