Introduction to Computer Science/3.8 Looping a Specific Number of Times with for Loops

3.8 Looping a Specific Number of Times with for Loops

🎯 Learning Goals for This Page
  • Explain the difference between a while loop and a for loop.
  • Use a for loop with the range() function to repeat a block of code a specific number of times.
  • Control the range() function using one, two, or three arguments.

A Better Way to Count

In the last lesson, we used a while loop to create a countdown. It worked, but we had to manually create a counter variable, check it, and remember to update it inside the loop. For situations where you know exactly how many times you want to loop, Python provides a much cleaner and safer tool: the for loop.

When to use `while` vs. `for`:
  • Use a while loop when you don't know the number of repetitions (e.g., loop while the user hasn't guessed the number).
  • Use a for loop when you know the exact number of repetitions (e.g., loop for 10 times).

The for Loop with range()

The most common way to use a for loop is to iterate over a sequence of numbers generated by the range() function. The range() function can be used in three ways:

1. range(stop): Loops from 0 up to (but not including) the stop number. This is the most common use.

for i in range(5):  # This will loop 5 times. The variable 'i' will be 0, 1, 2, 3, 4.
    print(i)

2. range(start, stop): Loops from the start number up to (but not including) the stop number.

for i in range(2, 6): # 'i' will be 2, 3, 4, 5.
    print(i)

3. range(start, stop, step): Loops from start to stop, but increments by the "step" value each time. The step can be negative to count down!

for i in range(10, 0, -2): # 'i' will be 10, 8, 6, 4, 2.
    print(i)

Live Example: Exploring range()

The best way to understand range() is to see it in action. The Trinket below shows all three methods. Run it, then follow the "Your Turn" instructions printed at the end to experiment with the code yourself.

Python 3Initializing...
Loading code editor...
Program output will appear here...
Safer and Cleaner

A for loop is often safer than a while loop for counting because it handles the counter variable (i) for you automatically. You don't need to initialize it before the loop or update it inside the loop, which means it's impossible to accidentally create an infinite loop!

Interactive Sandbox

Use this space to practice writing code and complete the "Your Turn" activities above.

Python 3Initializing...
Loading code editor...
Program output will appear here...