For Loops
A for loop runs the same block of code once for each item in a collection. It saves you from writing the same lines over and over.
Looping a set number of times
To repeat something a fixed number of times, loop over range().
See The range() function.
for i in range(3): print("hello")This prints hello three times. The indented line is the loop's body. It runs once each time round.
Looping over a list
rolls = [3, 5, 2]for roll in rolls: print(roll)roll is a variable that takes each value in turn — first 3, then 5, then
2. The indented block runs once per item.
Stop early with break
break ends the loop straight away, even if range() has numbers left. Put it inside an if so the loop stops only when something happens.
for count in range(1, 11): print(count) if count == 3: breakprint("Loop finished")This prints 1, 2 and 3. Numbers 4 to 10 never run. The program carries on after the loop.
See also: break and continue, Lists, The accumulator pattern.
Your turn
Print the numbers from 1 upwards, but use break to stop the loop straight after printing 4.
1 2 3 4
for number in range(1, 11): print(number) # add an if with a break inside it (two lines)Advanced reading
- Loop with index and value — get each item's position too, with
enumerate(). - Loop over lists together — walk two lists side by side with
zip(). - for and else — run code only when the loop finished without a
break.