Loops
12 min
Python has two loop constructs: for, which iterates over any sequence
(strings, lists, ranges...), and while, which repeats as long as a
condition holds.
for i in range(5):
print(i) # 0 1 2 3 4
n = 0
while n < 3:
print(n)
n += 1
Most of the time you'll reach for for — it's harder to accidentally write
an infinite loop with it.
A for loop accumulating a running total — one of the most common loop shapes you'll write.
Two keywords change a loop's flow:
break— exit the loop immediately.continue— skip to the next iteration.
range(start, stop, step) is the usual way to loop a fixed number of
times — range(5) is 0..4, range(2, 10, 2) is even numbers 2..8.
Write a function `sum_to_n(n)` that returns the sum of all integers from 1 to n (inclusive), using a loop.
Write a function `count_vowels(s)` that returns how many characters in the string s are vowels (a, e, i, o, u — case-insensitive), using a loop.
What values does `range(3)` produce when iterated?
You can write for/while loops and use break/continue to control them.