"unresolved reference" in ternary if else one liner

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.

>Solution :

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.

Leave a Reply