Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.4 — for Loops and range()
Python · Example 1 of 2

Looping over lists, strings and ranges

Change range(1, 101) to range(1, 100) and see how the total drops by exactly 100. That is an off-by-one error.

A for loop visits each item of a sequence one by one, and range(start, stop, step) produces the numbers for counting loops. range stops before stop and is lazy: it never builds the whole list in memory.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Print the squares of 1 to 5, one per line, with a for loop and range.

02

Add up the even numbers from 2 to 20 and print Total: 110.

03

Print a countdown 10, 7, 4, 1 using range with a negative step.

04

Count how many vowels (a, e, i, o, u) are in the text "education" and print Vowels: 5.

Explain it without notes

01

Explain what range(2, 10, 3) produces and why 10 does not appear.

02

What is an off-by-one error? Give an example with range.

03

Why is range(1_000_000_000) cheap, and how do you see its numbers?

04

What does a for loop do when the collection is empty?

Looping over lists, strings and ranges
Sign in to run this example in your browser.

Expected output

Fruit: apple
Fruit: banana
Fruit: cherry
H
i
!
[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[0, 5, 10, 15]
[5, 4, 3, 2, 1]
Sum of 1..100: 5050