1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

for loops & range

A for loop walks through a sequence, one item per iteration. range makes a sequence of numbers:

range(5)          # 0 1 2 3 4       (stop is excluded)
range(2, 6)       # 2 3 4 5
range(0, 10, 3)   # 0 3 6 9         (step of 3)
for i in range(3):
    print("Hi", i)

A loop is perfect for building up a total: start at 0 and add on every pass.

See it run

total = 0
for i in range(1, 5):
    total = total + i
print("Total:", total)

A running total, built one pass at a time. The table gets a new row whenever a value changes.

Practice for loops & range

Exercise 1

  • Print the even numbers 2 to 10 (one per line) using range with a step.
  • Then, with another loop, make total the sum of 1 to 100 (5050).

Exercise 2

Label every third locker from 3 through 18 inclusive with a for loop and range. Print one locker per line and store their sum in locker_total.

Exercise 3

A cinema sells rows 1 through 5. Row n has n * 4 seats. Use a for loop over range to print Row 1: 4 through Row 5: 20, and store the combined capacity in capacity.

Exercise 4

Predict, then verify. Read this program before running it:

total = 0
for n in [4, 7, 2, 9]:
    total += n * 2

What is total right after the loop's third pass? Guess first. Then run the program, press Step through your code in the result card, and press Next while watching the total box: it changes once per pass. Set prediction to its third new value, typed as a number.

The explanation and tasks are public. Running this lesson requires an account with course access.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest