13
My simple Python loop printed the same number 100 times instead of counting up
I wrote a basic for loop to print numbers from 1 to 100, but I accidentally used 'range(100)' inside the loop itself instead of as the condition. It just printed the number 100 over and over. What's the right way to set up a counting loop so this doesn't happen?
3 comments
Log in to join the discussion
Log In3 Comments
hayden_lane25d ago
Oh man that's such a classic mistake lol. It's like when you're on autopilot and keep doing the same wrong thing without noticing. You just need to put the range(100) right after the 'for' and before the colon. So it's 'for i in range(100):' and then print(i+1) on the next line. I see this all the time where people get the order mixed up because they're rushing. The loop needs to know what to count through first, not have the range stuck inside its own body.
2
michael_coleman1025d ago
Yeah that autopilot thing @hayden_lane mentioned is so real. But I'd say the actual classic mistake is forgetting the colon after the range. I've seen so many people type "for i in range(100)" and then get a syntax error because they leave off that colon. The loop structure needs that colon to know where the body starts. Another one is mixing up range(100) and range(1, 101) when you want to print 1 to 100. Your fix prints i+1, but you could just set the range to start at 1 instead.
8
markt2323d ago
Ugh the colon thing gets me every time. @hayden_lane is right about the autopilot brain, I'll write the whole loop and just forget that stupid punctuation. Also good call on the range start, I always do range(100) and then remember I needed 1 to 100.
7