LESSON 08 · BEGINNER PATH11 min

Loops

Repeat work with for and while loops and recognize when a loop stops.

Video coming to YouTube

Work through the full lesson and run its code while the video is being prepared for publication.

Understand the concept

A for loop visits items in a sequence. range(1, 4) produces 1, 2, and 3; the stop value is excluded. A running total is a common reason to loop.

A while loop repeats while its condition remains true. Its body must eventually change something that makes the condition false. break can end a loop early when needed.

  • for iterates over values
  • range stop is excluded
  • while needs a stopping condition

See it step by step

Read the code, predict the output, then compare it with the result.

01. Visit a range

PYTHON
for number in range(1, 4):
    print(number * 2)
EXPECTED OUTPUT
2
4
6

range(1, 4) provides 1, 2, and 3; the stop value 4 is excluded.

02. Accumulate a total

PYTHON
total = 0
for value in [2, 3, 4]:
    total += value
print(total)
EXPECTED OUTPUT
9

Each iteration adds the next list item to total. The final print runs after the loop.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnChange the loop to add the numbers 1 through 5. Print the final total and check that it is 15.
Need a hint?

range(1, 6) produces 1 through 5. Keep total += number inside the loop, then print the final total after the loop.

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.Which values does range(3) produce?

    02.How many times does for x in range(2, 5) run?

    03.What does break do inside a loop?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    A while loop never progresses

    COMMON MISTAKE
    count = 0
    while count < 3:
        print(count)
    FIX
    count = 0
    while count < 3:
        print(count)
        count += 1

    What happens: The condition stays true, so the loop keeps printing 0.
    Update the value tested by the condition.

    Expecting the stop value

    COMMON MISTAKE
    for n in range(1, 4):
        print(n)
    # Expecting 1, 2, 3, 4
    FIX
    for n in range(1, 5):
        print(n)

    What happens: Only 1, 2, and 3 appear.
    range excludes its stop argument.