Course contentsShow
← Python
Lesson 85 of 1,0602. Control Flow and LogicFree lesson

Generating Numeric Sequences with Range

Learners will be able to create specific numeric ranges to control the exact number of repetitions for a code block.

Mastering Numeric Sequences with range()

In this lesson, you will learn how to use the range() function to precisely control how many times a block of code repeats.

So far, you have used for loops to iterate over items already inside a list or a string. But what if you want to perform an action exactly 10 times, even if you don't have a list of 10 items? This is where the range() function becomes your best friend.

How range() Works

Think of range() as a machine that generates a sequence of numbers on command. When you pass a single integer to range(n), it creates a sequence starting from 0 and stopping just before it hits n.

If you want a loop to run exactly 5 times, you write it like this:

# The loop will assign values 0, 1, 2, 3, 4 to 'i'
for i in range(5):
    print("This code will run 5 times!")

Why Stop Before the Number?

You might notice that range(5) generates numbers up to 4, not 5. This is a common pattern in programming called "zero-indexing." Because Python starts counting at 0, the sequence 0, 1, 2, 3, 4 contains exactly five numbers. This makes it incredibly easy to keep track of your progress while looping.

Controlling the Start and Step

You don't always have to start at 0. If you need a different range, you can pass two or three arguments:

  • range(start, stop): Generates numbers from start up to (but not including) stop.
  • range(start, stop, step): Does the same as above, but jumps by the step amount each time (e.g., range(0, 10, 2) gives you 0, 2, 4, 6, 8).

Using range() gives you total control over your logic, allowing you to execute tasks based on the number of repetitions you need, rather than the contents of an existing container.

Key Takeaway: Use the range() function to generate a specific sequence of numbers, giving you exact control over the number of iterations in your for loops.