Loops: doing things again and again
Computers never get bored. Use for, range and while to repeat steps, and to add up or check many values in one go.
In 60 seconds
Loops: doing things again and again
Computers never get bored. Use for, range and while to repeat steps, and to add up or check many values in one go.
The for loop
for loop goes through a group of values one at a time. Each time round, the loop variable holds the next value, and the indented lines run again.runs = [4, 6, 1, 0, 4]
for r in runs:
print("This ball:", r)
print("Over finished!")r is 4, then 6, then 1, then 0, then 4. The last line is not indented, so it runs once, after the loop ends.Counting with range
range() makes a sequence of whole numbers to loop over.| Code | Numbers it gives | Remember |
|---|---|---|
range(5) | 0, 1, 2, 3, 4 | Starts at 0 and stops before 5 |
range(1, 6) | 1, 2, 3, 4, 5 | Start at 1, stop before 6 |
range(2, 11, 2) | 2, 4, 6, 8, 10 | The third number is the step |
for i in range(1, 11):
print(f"7 x {i} = {7 * i}")Adding up with a loop
- 1
Start
total = 0 - 2
Loop
For each value in the list… - 3
Update
total = total + value - 4
After the loop
total now holds the sum of everything.
runs = [4, 6, 1, 0, 4, 2]
total = 0
for r in runs:
total = total + r # you can also write: total += r
print("Runs in the over:", total)sum() that does this in one step. But knowing the running-total pattern lets you do things sum() cannot, like counting only boundaries, or stopping early.runs = [4, 6, 1, 0, 4, 2]
boundaries = 0
for r in runs:
if r == 4 or r == 6:
boundaries += 1
print("Boundaries:", boundaries)The while loop
while loop repeats as long as a condition is True. Use it when you do not know in advance how many times to repeat.savings = 0
weeks = 0
while savings < 1000: # target in rupees
savings = savings + 150 # pocket money saved each week (made-up)
weeks = weeks + 1
print(f"After {weeks} weeks you have Rs {savings}.")while loop must change something so its condition becomes False one day. If you forget savings = savings + 150, the condition stays True forever. That is an infinite loop, and the page may freeze. If that happens, reload the page, fix the code and run again.Two useful words: break and continue
breakstops the loop straight away.continueskips the rest of this round and moves to the next value.
balls = ["1", "4", "0", "W", "6"]
for b in balls:
if b == "W":
print("Wicket! Stop.")
break
print("Runs:", b)Watch and read more
Lab
Two loop functions: a times table and a total-runs counter, written without shortcuts.
The problem
Fix the two functions in the starter:
table(n)should return a list of the first 10 multiples ofn. For exampletable(7)gives[7, 14, 21, …, 70]. Right now it stops too early: look at therange.total_runs(scores)should add up all the numbers in the list and return the total, using aforloop and a running total. Do not usesum()here; the point is to practise the loop. An empty list should give 0.
Press Run to see the output, then Check.
Practice lab
Edit the code and run it. Python runs in your browser — nothing is sent to our server.
No output. Add print(...) to see values.
You are done when
Hard questions
Try to answer before you reveal. If you can answer these, you understood the lesson.
Q1Write a loop that finds the highest score in a list without using max(). What should the starting value be?Reveal
A safe start is the first item: best = scores[0]. Then loop and replace best whenever you find a bigger value. Starting at 0 would fail if every score were negative, like temperatures in winter. (An empty list needs its own rule, since it has no highest value.)
Q2Use a while loop to answer: how many balls does a batter need to reach 50 runs if they score 4 on every ball? Why is a while loop a good fit?Reveal
runs = 0; balls = 0, then while runs < 50: runs += 4; balls += 1. It ends with 13 balls (52 runs). A while loop fits because we do not know the number of rounds in advance; we only know when to stop.
Questions people ask
Why does range(5) stop at 4?
range(5) gives 5 numbers, starting at 0: 0, 1, 2, 3, 4. Python usually counts from 0. It feels odd at first, but it makes many things simpler later, like positions in a list.
When should I use for and when while?
Use for when you are going through a known list or a known count. Use while when you repeat until something happens, such as reaching a target, and you do not know how many rounds it will take.
What does += mean?
total += r is a short way to write total = total + r. There are also -=, *= and others.
My loop printed only once. Why?
Check the indentation. Lines that should repeat must be indented under the for line. Also check that you did not put return or break inside the loop by mistake.
Lesson test
5 questions. Get 3 right (60%) to pass and complete this lesson.