Python Basics · Lesson 7 of 12

For Loops

A loop repeats a block of code. Python's for loop runs the block once for each item in a sequence.

The simplest sequence is a run of numbers, made with range():

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

That prints 0, 1, 2, 3, 4. Like if, the line ends with a colon and the block is indented.

How range counts

range has a quirk worth learning now: it starts at 0 and stops before the number you give.

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

With two numbers, the first is where to start and the second is where to stop (not included). A third number is the step.

The variable after for, here i, takes each value in turn. You can name it anything.

Building up a result

Create a variable before the loop and update it inside:

total = 0
for n in range(1, 5):
    total += n
print(total)   # 1 + 2 + 3 + 4 = 10

Note where the print is. It is not indented, so it runs once, after the loop is finished. Indent it, and it would run on every round.

Looping over a string

A string is a sequence of characters, so for works on it too:

for letter in "cat":
    print(letter)

Your Task

  1. Use a for loop with range to print the numbers from 1 to 10, one per line.
  2. In the same loop, add each number to total.
  3. After the loop, print total.
  • The code uses a for loop with range
  • The numbers 1 to 10 are printed in order, one per line
  • total ends up as 55
  • The total is printed once, after the loop