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.
Print the squares of 1 to 5, one per line, with a for loop and range.
Add up the even numbers from 2 to 20 and print Total: 110.
Print a countdown 10, 7, 4, 1 using range with a negative step.
Count how many vowels (a, e, i, o, u) are in the text "education" and print Vowels: 5.
Explain it without notes
Explain what range(2, 10, 3) produces and why 10 does not appear.
What is an off-by-one error? Give an example with range.
Why is range(1_000_000_000) cheap, and how do you see its numbers?
What does a for loop do when the collection is empty?
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