I1 · Python Programming for AI

for Loops and range()

A for loop repeats a block of code once for each item in a sequence, such as a list, a string or a range. range(stop) produces the whole numbers from 0 up to, but not including, stop; range(start, stop, step) lets you choose where to start and how far to jump.

10 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

How do you print the table of 7 without writing ten print lines?

A for loop repeats a block of code once for each item in a sequence, such as a list, a string or a range. range(stop) produces the whole numbers from 0 up to, but not including, stop; range(start, stop, step) lets you choose where to start and how far to jump.

In simple words

for n in range(1, 11): means 'for n = 1, 2, 3 … 10, do the indented steps'. Python sets n to each value in turn. A for loop over a list visits every item, so for name in names: greets everyone without knowing how many names there are.

Why it matters

Computers are valuable because they repeat work tirelessly. Loops process every row of a dataset, every word in a document and every training step of a model.

How it works

CallNumbers produced
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 10, 2)0, 2, 4, 6, 8
range(5, 0, -1)5, 4, 3, 2, 1

enumerate() gives both the position and the item, and is handy when you need a counter.

In code

A times table with range, a loop over a list, and a running total.

times_table.py
for n in range(1, 11):
    print(7, "x", n, "=", 7 * n)

fruits = ["mango", "banana", "guava"]
for position, fruit in enumerate(fruits, start=1):
    print(position, fruit)

total = 0
for marks in [72, 85, 64]:
    total += marks
print("Total marks:", total)

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
1 mango
2 banana
3 guava
Total marks: 221

Try it yourself

How many times does it run?

Match each loop header to the numbers it goes through.

  • for i in range(3):
  • for i in range(2, 5):
  • for i in range(1, 10, 3):
  • for i in range(3, 0, -1):

Put the lines in order

Arrange these lines into a program that prints the squares of 1 to 5 and then 'Done'. Indentation is shown.

  1. 1 print(n, square)
  2. 2 square = n * n
  3. 3print("Done")
  4. 4for n in range(1, 6):

Common mistakes

  • Expecting range(1, 10) to include 10.
  • Changing a list while looping over it.
  • Forgetting to indent the loop body, or indenting a line that should run after the loop.

Check yourself

Question 1

1. How many times does for i in range(5): run?

Question 2

2. What is the last number in range(2, 9, 2)?

Question 3

3. What does enumerate() add to a loop?

Summary

  • for repeats a block once for each item in a sequence.
  • range(start, stop, step) stops before stop.
  • enumerate gives positions; a running total adds as it goes.

Finished reading?

Sources: W3Schools: Python For Loops