Python 3D Academyবাংলা

for and range()

🌍 In real life. A teacher calls the roll: roll 1, roll 2, roll 3, … up to the last student. The teacher knows exactly how many names there are before starting, and calls each number once.

When you know the values a loop should go through, for is the loop to use.

The idea in one sentence: for takes each value from a sequence, like range(4), puts it in the loop variable, and runs the block once for each value.

Its words:

  • loop variable: the name after for, like i, which holds the current value
  • range(stop): the numbers 0, 1, 2, … up to just before stop
  • range(start, stop, step): start somewhere else, and jump by step; a negative step counts down

Step by step, for for i in range(4)::

  1. range(4) gives 0, 1, 2, 3.
  2. i gets 0, and the block runs. Then i gets 1, and the block runs again.
  3. The same for 2 and 3.
  4. No values are left, so the loop ends.
for i in range(4):
    print(i)

range(start, stop) starts somewhere else, and a third number is the step: range(start, stop, step). A negative step counts down. You don't even have to use the loop variable:

for n in range(1, 4):
    print(n, "squared is", n * n)

for i in range(3):
    print("Hip hip hooray!")
for n in range(10, 0, -3):
    print(n)
range never reaches its stop number, so 0 is not included.

Why the stop is left out. As with slices, it keeps the counting tidy: range(n) gives exactly n values, and range(a, b) gives b - a values. range(4) is "4 laps".

What it costs. range doesn't build a list of numbers first; it hands them out one at a time. So range(1000000) takes almost no memory. The loop still does one lap per number, so a million numbers means a million laps.

for or while? Use for when you know the values (a range, a word, a list). Use while when you only know when to stop.

The same loop can work with numbers you read from the user:

n = int(input("Table of: "))
for i in range(1, 4):
    print(f"{n} x {i} = {n * i}")

Mistakes and edge cases.

  • Expecting the stop number. range(1, 10) ends at 9. Write range(1, 11) to include 10.
  • Counting down without a negative step. range(5, 1) is empty, so the loop never runs. Write range(5, 1, -1).
  • A decimal step. range(0, 1, 0.5) gives TypeError: 'float' object cannot be interpreted as an integer.
  • Looping over a number. for i in 5: gives TypeError: 'int' object is not iterable. Write range(5).
  • Changing the loop variable. Setting i = 10 inside the block doesn't skip ahead: on the next lap, for gives i the next value anyway.

Quiz

  1. What does this print?

    for i in range(2, 5):
        print(i)
  2. How many numbers does range(1, 10) give?

    • 9
    • 10
    • 11
  3. What does this print?

    for i in range(0, 10, 4):
        print(i)
  4. What does this print?

    total = 0
    for i in range(1, 4):
        total += i
    print(total)
  5. Which line has a mistake?

    for i in range(3):
    print(i)

Coding tasks

  1. Print the even numbers from 2 to 20, one per line. Use range() with a step.

  2. Ask for a whole number n. Print its times table from 1 to 5, in this form:

    3 x 1 = 3
    3 x 2 = 6
    
  3. Ask for a whole number n. Print a triangle of stars: 1 star on the first line, 2 on the second, up to n.