Counting made easy
Discover the range() function โ your best friend for counting and repeating in loops.
The range() function generates a sequence of numbers. You can use it with for loops to count from 1 to 10, from 0 to 100, or even count by 2s or 5s. It is the most common companion of the for loop!
๐ก Think of it like this:
Think of range like a number line maker. You say "give me numbers from 1 to 10" and range creates them for you. Then your for loop walks through each number one at a time.
Range is essential for counting loops. Whether you are repeating an action 50 times or counting from 0 to 100 by steps of 10, range makes it simple and clean.
Where you see this in real life:
range(1000000) creates a million numbers instantly, but Python barely uses any memory because it generates them one at a time!
range()generates a sequence of numbers. It is the best friend of the for loop! You can use it in three different ways.
Gives you numbers from 0 up to (but not including) the stop number.
Starts at 0, stops before 5Gives you numbers from start up to (but not including) stop.
Starts at 3, stops before 8The third number is the step โ how much to jump each time!
Click โถ Run to see the output!| Code | Numbers Generated |
|---|---|
| range(5) | 0, 1, 2, 3, 4 |
| range(2, 6) | 2, 3, 4, 5 |
| range(0, 10, 2) | 0, 2, 4, 6, 8 |
| range(10, 0, -1) | 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 |
| range(1, 20, 5) | 1, 6, 11, 16 |
What numbers does range(2, 10, 2) produce?