Learn Python · lesson 19 of 60 · about 8 minutes
for Loops and range()
Ask for each of today's tasks and number them: go through text with for, and count with range(start, stop, step).
What you'll learn
- Loop over a string with for
- Generate numbers with range()
- Use start, stop and step
One question per task
Now the assistant knows how many tasks Sam has. It should ask for each one by number and print a numbered list: 1. water the plants, 2. call grandma. This time the number of laps is known before the loop starts, which is the job of a for loop.
for visits each item
A for loop takes each item from a sequence in turn and runs its block once per item. With a string, each item is one character.
One character at a time
for letter in "Hi!":
print(letter)Output
H
i
!Counting with range()
range() produces numbers for a for loop:
range(5)gives 0, 1, 2, 3, 4 (it stops before 5)range(2, 6)gives 2, 3, 4, 5range(10, 0, -3)gives 10, 7, 4, 1 (the third number is the step)
Three kinds of range
for i in range(3):
print(i)
for i in range(2, 9, 3):
print(i)Output
0
1
2
2
5
8A numbered list of today's tasks
tasks = 2
for number in range(1, tasks + 1):
job = input(f"Task {number}? ").strip().lower()
print(f"{number}. {job}")
Output
Task 1? 1. water the plants
Task 2? 2. call grandmaWhy tasks + 1?
range() stops before its second number, so range(1, tasks) would ask for one task too few. range(1, tasks + 1) runs from 1 up to and including tasks. And when tasks is 0, range(1, 1) is empty, so the loop doesn't run at all.
Tip
Use for when you know how many times to repeat, or have a sequence to go through. Use while when you repeat until something happens.
Now try it yourself
This lesson is free in Codiqo, with 12 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.