0
Why this loop code is wrong and cannot printïŒ
The code below, putting "i+=1" after continue, it cannot print, but when I change its position to put it after the variable age, it run well, what the different between these 2 positions? Thank you in advance. total = 0 i = 1 while i <= 5: age = int(input()) if age >= 3: total += 100 else: continue i +=1 print(total)
1 Answer
+ 6
Because when the increment i += 1 is down there, it will not be processed once `continue` has been issued. And by that, <i> is never incremented (remains to be 3), and you're stuck in an infinite loop.
But if you move it up after reading <age>, then `continue` will not prevent the increment i += 1 from being processed, and it's safe.
You can also remove the `else` block entirely and it will still work the same way.