Skip to content

Beginner · Loops: repeating work · topic 9 of 50 · 25 min

for loops and range()

Explanation

A for loop repeats a block of code once for each item: each character of a string, or each number from range(). range(5) gives 0, 1, 2, 3, 4, and range(start, stop, step) lets you choose where to start, where to stop and how big each jump is. The stop number itself is never included.

Why loops?

Suppose you want to print the numbers 1 to 100. Writing 100 print lines is slow and boring. A loop is a way to tell Python "repeat this block many times". Each single run of the block is called an iteration, or a round.

Think of it like this: Think of a teacher taking attendance. She does the same thing for every student on the register: read the name, wait for "Present", tick the box. She does not need different instructions for each student. A for loop works the same way: one set of steps, repeated for each item.

Looping over a string

python
for letter in "CHAI":
    print(letter)
Prints C, H, A and I, each on its own line.

Read it as "for each letter in CHAI, do this". letter is the loop variable: a variable that Python fills with the next item at the start of every round. You can give it any name. The for line ends with a colon, and the block inside is indented by 4 spaces, just like an if.

range(): a row of numbers

range() is a built-in function that produces whole numbers one by one. range(5) gives 0, 1, 2, 3 and 4: five numbers, starting at 0 and stopping just before 5.

python
for i in range(5):
    print("Round", i)
Prints Round 0 up to Round 4. The number 5 itself is not included.

range can take three numbers: range(start, stop, step). start is the first number, stop is where it stops (not included), and step is how much to add each time. A negative step counts backwards.

CallNumbers it gives
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(2, 11, 2)2, 4, 6, 8, 10
range(10, 0, -1)10, 9, 8, ... 1
range(0, 20, 5)0, 5, 10, 15
python
for n in range(2, 11, 2):
    print(n, end=" ")
print()
for n in range(5, 0, -1):
    print(n, end=" ")
print("Go!")
Prints 2 4 6 8 10 on one line, then 5 4 3 2 1 Go!. end=" " keeps the numbers on one line.
Careful: The off-by-one mistake: range(1, 10) stops at 9, not 10. If you want 1 to 10, write range(1, 11). Ask yourself "is the last number included?" every time you write a range.

Using the loop variable

python
total = 0
for day in range(1, 8):
    total = total + 150
    print(f"Day {day}: mess bill so far Rs {total}")
The loop variable day changes from 1 to 7. The total grows by 150 each round.
Tip: A preview: a for loop can also go through a list, which is a group of values in square brackets, like for item in ["rice", "dal", "oil"]. You will learn lists in a later module. For now we loop over strings and ranges.
python
for item in ["rice", "dal", "oil"]:
    print("Buy", item)
A first look at looping over a list. Prints Buy rice, Buy dal, Buy oil.

Watch the lesson

for loops and range() · 1/6

for loops and range

In this lesson you will learn the for loop, which repeats work for you, and range, which gives you numbers to loop over.

Prefer a video by a teacher? Find free videos on “python for loop range tutorial for beginners” on YouTube ↗

In real life: A rocket launch countdown

Before a rocket lifts off from Sriharikota, the control room counts down from 10 to 1. A for loop with a negative step does the same countdown in three lines, and it never skips or repeats a number.

python
for second in range(10, 0, -1):
    print(second)
print("Liftoff!")
Prints 10 down to 1, then Liftoff!.

Practice (0/3 done)

Task 1 · Code · Python

The function sum_to(n) should add up all numbers from 1 to n, so sum_to(5) is 1 + 2 + 3 + 4 + 5 = 15. It has an off-by-one bug. Fix it.

Task 2 · Code · Python

Write a function count_vowels(word) that loops over the word and counts the vowels a, e, i, o and u. Capital vowels count too. Example: count_vowels("India") returns 3.

Task 3 · Code · Python

Write a function sum_evens(limit) that returns the sum of the even numbers from 2 up to limit (limit included if it is even). Use range with a step of 2. Example: sum_evens(10) is 2 + 4 + 6 + 8 + 10 = 30.

Quick quiz

Question 1

1.Which numbers does range(4) give?

Question 2

2.Which numbers does range(2, 10, 3) give?

Question 3

3.How many times does the block of for ch in "Pune": run?

Question 4

4.Which range counts 5, 4, 3, 2, 1?

Question 5

5.What is the last number printed by for i in range(1, 10): print(i)?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: if, elif and else