TutreNews Learn

Decisions and loops

for loops and range

Goal: Iterate over ranges and sequences · 9 min

A for loop goes through the elements of a sequence one by one:

for letter in "abc":
    print(letter)

range produces number sequences:

  • range(5) → 0, 1, 2, 3, 4 (5 is excluded)
  • range(2, 6) → 2, 3, 4, 5
  • range(10, 0, -3) → 10, 7, 4, 1

Use for when you know what to iterate over; use while when you repeat until a condition changes.

Worked example: Multiplication table row

  1. range(1, 6) gives 1 … 5.
  2. Each value is multiplied by 7.
  3. end=" " keeps everything on one line.
for i in range(1, 6):
    print(i * 7, end=" ")

Output:

7 14 21 28 35