Python from zeroBeginnerLesson 1027 min read

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.

Lesson in motion

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.

1/5
In simple words
Your teacher asks you to write "I will do my homework" 100 times. That would take you ages. A computer can do it in a blink, if you tell it once: "repeat this 100 times". That instruction is called a loop.

The for loop

A 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.
Python: loop over a list of runspython
runs = [4, 6, 1, 0, 4]
for r in runs:
    print("This ball:", r)
print("Over finished!")
The loop runs 5 times, once per value in the list. 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.
CodeNumbers it givesRemember
range(5)0, 1, 2, 3, 4Starts at 0 and stops before 5
range(1, 6)1, 2, 3, 4, 5Start at 1, stop before 6
range(2, 11, 2)2, 4, 6, 8, 10The third number is the step
Python: the 7 times tablepython
for i in range(1, 11):
    print(f"7 x {i} = {7 * i}")

Adding up with a loop

A very common pattern: start a running total at 0, then add each value to it inside the loop.
  1. 1

    Start

    total = 0
  2. 2

    Loop

    For each value in the list…
  3. 3

    Update

    total = total + value
  4. 4

    After the loop

    total now holds the sum of everything.
Python: total runs in an overpython
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)
Python has a built-in 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.
Python: counting with a conditionpython
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

A while loop repeats as long as a condition is True. Use it when you do not know in advance how many times to repeat.
Python: saving up for a cricket batpython
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}.")
Danger
A 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

  • break stops the loop straight away.
  • continue skips the rest of this round and moves to the next value.
Python: stop at the first wicketpython
balls = ["1", "4", "0", "W", "6"]
for b in balls:
    if b == "W":
        print("Wicket! Stop.")
        break
    print("Runs:", b)
Try this. Change the times table to print the 13 times table, but only up to 13 x 5. You only need to change two numbers. 🎉

Watch and read more

Lab

Two loop functions: a times table and a total-runs counter, written without shortcuts.

~12 min

The problem

Fix the two functions in the starter:

  1. table(n) should return a list of the first 10 multiples of n. For example table(7) gives [7, 14, 21, …, 70]. Right now it stops too early: look at the range.
  2. total_runs(scores) should add up all the numbers in the list and return the total, using a for loop and a running total. Do not use sum() 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.

Output

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.

Please sign in to continue.

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.

Sign in to take the test and save your progress