print("TOP")
= 0
counter while counter < 5: # CONDITION
print("-------")
print(counter, "Hello")
+= 1 # INCREMENT THE COUNTER
counter # NOTHING ELSE, START THE LOOP OVER
print("BOTTOM")
17 While Loops, Counters, and Accumulators
As mentioned, with a "while" loop, we can execute a statement of code over and over as long as some condition is true.
It is possible to set up an infinite loop, although this will never stop and is problematic in practice:
while True: # INFINITE LOOP (PROBLEMATIC)
print("-------")
print("Hello")
For this reason, we can use a condition to tell the loop when to stop. Often this is used in conjunction with a counter variable:
We can alternatively use control statements like break
(to break out of the loop), and continue
(to go to the next iteration of the loop):
print("TOP")
= 0
counter while True: # RETURN OF THE INFINITE LOOP
print("-------")
print(counter, "Hello")
+= 1 # INCREMENT THE COUNTER
counter
if counter >= 5:
break # BUT WHEN THIS CONDITION IS REACHED WE STOP
# NOTHING ELSE, START THE LOOP OVER
print("BOTTOM")