When I run the below code, I get two different values for i. Why?
The only difference is the first uses i = i + 1
whereas the second uses i += 1
which are equivalent in all other use cases I've seen.
i = 1
k = 2
i = i + 1 if i == k else k
print(i) # prints 2
i = 1
k = 2
i += 1 if i == k else k
print(i) # prints 3
According to Python's operator precedence rules, in the first example the ternary expression applies to
i + 1
. So the followingis equivalent to
Whereas the following
is equivalent to