Lesson 20/48 ยท ๐ Loops & Repetition
๐ Loops & RepetitionLesson 20/48
Phase 3 ยท Loops & Repetition15 min
range(), Counting Made Easy
The function behind every for loop, master it separately first
In the next lesson you'll learn
So we're learning
for loops, the tool for repeating actions. But almost every for loop uses a function called range(), and beginners trip over it constantly.So we're learning
range() on its own first. Trust the process.range(stop), count from 0
This trips up everyone at first. Remember: range stops before the number you give it.
range(n) generates numbers starting from 0, up to (but NOT including) n.range(5) โ 0, 1, 2, 3, 4 (not 5, it stops before 5)This trips up everyone at first. Remember: range stops before the number you give it.
Visualizing range()python
# Easiest way to see what range produces:
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(3))) # [0, 1, 2]
print(list(range(1))) # [0]
print(list(range(0))) # [] (empty, nothing before 0)range(start, stop), control where you begin
range(1, 6) โ 1, 2, 3, 4, 5 (starts at 1, stops before 6)range(5, 10) โ 5, 6, 7, 8, 9range(0, 5) โ same as range(5)range(start, stop, step), skip numbers
The third argument controls the step size, how much to add each time.
The third argument controls the step size, how much to add each time.
range(0, 10, 2) โ 0, 2, 4, 6, 8 (even numbers)range(1, 10, 2) โ 1, 3, 5, 7, 9 (odd numbers)range(10, 0, -1) โ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 (countdown!)All three formspython
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(1, 6))) # [1, 2, 3, 4, 5]
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]๐คQuick Check
How many numbers does range(5) produce?
๐คQuick Check
What does list(range(2, 8, 2)) produce?
Practice Exercises
0/3 solvedExercise 1 of 3easy
โฑ 00:00Print a Range
Use list() and range() to print the numbers from 1 to 10 (inclusive).Expected output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
solution.py
1 / 3
Exercise 2 of 3easy
โฑ 00:00Even Numbers
Print all even numbers from 0 to 20 using range() with a step.Expected output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
solution.py
2 / 3
Exercise 3 of 3easy
โฑ 00:00Countdown!
Print a countdown from 5 down to 1 using range() with a negative step.Expected output: [5, 4, 3, 2, 1]
solution.py
3 / 3
Solve all 3 exercises to unlock completion