27
My Python script printed a number I didn't tell it to
I wrote a loop to count from 1 to 10, but it printed 11 at the end. I learned my condition was 'less than or equal to' instead of just 'less than'. Anyone else get tripped up by loop boundaries like that?
3 comments
Log in to join the discussion
Log In3 Comments
emery_white6d ago
My old car's odometer rolled over to 100,000 miles right after I sold it, which feels like the same off-by-one logic. I get what lindal13 means about building in that safety margin on purpose. It's just a good habit for avoiding little surprises, in code or anywhere else.
6
lindal136d ago
Oh yeah, that's a classic. I started writing my loops to end one number early on purpose. It just saves me from that exact headache every single time.
5
Yeah, ending loops early is such a solid fix. I do the same thing, especially when I'm pulling items from an array. I'll set the condition to `i < length - 1` right from the start. It just becomes automatic after you fix that off-by-one error a few times.
10