Beginner · Loops: repeating work · topic 9 of 50 · 25 min
for loops and range()
Explanation
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.
Looping over a string
for letter in "CHAI":
print(letter)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.
for i in range(5):
print("Round", i)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.
| Call | Numbers 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 |
for n in range(2, 11, 2):
print(n, end=" ")
print()
for n in range(5, 0, -1):
print(n, end=" ")
print("Go!")Using the loop variable
total = 0
for day in range(1, 8):
total = total + 150
print(f"Day {day}: mess bill so far Rs {total}")for item in ["rice", "dal", "oil"]:
print("Buy", item)Watch the lesson
for loops and range() · 1/6
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.
for second in range(10, 0, -1):
print(second)
print("Liftoff!")Practice (0/3 done)
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.
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.
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
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.