Flow controls: Loops · 5 / 26 Theory

break, continue and while True

Sometimes you have to leave a loop before it ends, or skip a turn. That is what break and continue are for.

break: leaving the loop

for i in range(1, 100):
    if i * i > 50:
        break
    print(i)
# 1 2 3 4 5 6 7

continue: jumping to the next turn

for i in range(1, 8):
    if i % 2 == 0:
        continue    # even numbers are skipped
    print(i)
# 1 3 5 7

while True: a loop with an exit in the middle

while True repeats forever, and you leave with break when something happens. It is the natural way to validate an input:

while True:
    age = int(input())
    if 0 <= age <= 120:
        break
    print("Invalid age, try again")

print("Age saved:", age)

With this you solve While loop with validated input and Access control (repeat until the password is right).

Loops that never end

The exercises Infinite divisions, Infinite number sum and Infinite multiplication tables ask you to repeat until the user decides to stop, for example by typing an exit word or a sentinel value:

total = 0
while True:
    text = input()
    if text == "end":
        break
    total += int(text)
print(total)

else in a loop

A loop can have an else that runs only if it finished without going through a break. It is ideal for searching:

n = int(input())
for d in range(2, n):
    if n % d == 0:
        print("Not prime")
        break
else:
    print("Prime")   # (for n >= 2)

Practice with Prime number, Repeated number and Access control.