1

Why does idcter not reset to 0 when it exceeds maxid?

maxid=9999 idcter=9999 idcter += 1 if(idcter <= maxid) else 0 print('this is good: ' + str(idcter)) idcter += 1 if(idcter <= maxid) else 0 print('now this is weird: ' + str(idcter)) idcter=10000 idcter = idcter + 1 if(idcter <= maxid) else 0 print("that's better: " + str(idcter)) 

Output:

this is good: 10000 now this is weird: 10000 that's better: 0 

So it's a simple fix, but why would idcter not reset after it exceeds maxid?

3
  • Which line are you confused by? Commented Aug 29, 2018 at 15:38
  • Are you just expecting that += 0 will do the same thing as = 0? If it did, that would make += very unpredictable and hard to use… Commented Aug 29, 2018 at 15:40
  • If you think about it, it's impossible for idcter += 1 if idcter <= maxid else 0 to set the variable idcter to 0. Even if that statement would be parsed as (idcter += 1) if idcter <= maxid else 0, neither of the two if branches assigns 0 to idcter. The idcter += 1 branch increments it, and the 0 branch does nothing. There is no assignment in that branch. Commented Aug 29, 2018 at 15:40

1 Answer 1

11

The operator precedence of

idcter += 1 if (idcter <= maxid) else 0 

is visualized by the following grouping

idcter += (1 if (idcter <= maxid) else 0) 

which means you increment by 0 if the condition doesn't hold.

Compare that to

idcter = idcter + 1 if (idcter <= maxid) else 0 # == idcter = (idcter + 1) if (idcter <= maxid) else 0 

Where you assign 0 to the result in the same case.

BTW, 10000 already exceeds your maxid of 9999. One typical way to implement such a resetting increment uses the modulo operator. In your case:

idcter = (idcter+1) % (maxid+1) # 9997 -> 9998 -> 9999 -> 0 -> 1 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick answer. Additional thanks for the modulo tip!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.