The for Loop and range()

45 min read Conditional Statements and Loops

This is a free course. Log in to run the code exercises and track your progress.

The for Loop and range()

A loop repeats a block of statements. The for loop repeats once for every value in a sequence. range() produces a sequence of numbers:

  • range(5) gives 0, 1, 2, 3, 4 (it stops before 5).
  • range(1, 6) gives 1, 2, 3, 4, 5.
  • range(2, 11, 2) gives 2, 4, 6, 8, 10 (the third value is the step).
  • range(5, 0, -1) counts down: 5, 4, 3, 2, 1.
total = 0
for i in range(1, 11):
    total = total + i
print("Sum of 1 to 10 is", total)   # 55

The variable i takes each value in turn. Everything indented under the for line runs once per value; the print line is not indented, so it runs once, after the loop ends.

Python exercise

Read a number n and print its multiplication table from 1 to 10, one line each, like 7 x 1 = 7.

n = int(input())
for i in range(1, 2):  # fix the range so i goes from 1 to 10
    print(n, "x", i, "=", n * i)

Log in to edit and run this code.