break, continue and else
Inside any loop, break leaves the loop at once and continue skips the rest of the current pass. A loop can also end with an else block, which runs only if the loop finished without a break.
for n in [4, 9, 15, 21]:
if n % 2 == 0:
continue # skip evens
if n > 10:
print("stopped at", n)
break
print("odd", n)
else:
print("not printed: break ran")while True
When the exit test belongs in the middle of the loop, write while True and leave with break:
total = 0
while True:
total += 7
if total > 30:
break
print(total) # 35Read else on a loop as "no break happened". It fits searches: break when you find what you want, and put the not-found case in else. Keep loops short, so every break is easy to spot.
Your task
Write total_until_stop(numbers) that adds the numbers in order, skips negative ones, and stops at the first 0. Write smallest_divisor(n) for n of at least 2, returning the smallest divisor above 1 (which is n itself for a prime), trying d only while d * d <= n.
The explanation opens here once every check passes.