Python For Loops
for repeats the indented line once for each value. range(3) gives 0, then 1, then 2. The end number is not taken. cup holds the value for that pass. print(cup) writes it. Three passes, three lines.
for cup in range(3):
print(cup)
The screen shows 0, then 1, then 2. When the loop is finished, cup still holds 2. That is the last value. The name is not cleared.
range(1, 3) starts at 1 and stops before 3. The lines would be 1, then 2. The first number is taken. The second number is the end, and it is not taken.
A line level with for runs once, after
for letter in "tea" takes one letter each pass: t, then e, then a. print(letter) is indented, so it repeats. print("done") sits level with for, so it runs once, after the letters.
for letter in "tea":
print(letter)
print("done")
The screen shows t, then e, then a, then done.
Three rows. The end number of range is not taken.
📊 What each pass gets
| Source | Lines |
|---|---|
| range(3) | 0, then 1, then 2 |
| range(1, 3) | 1, then 2 |
| "tea" | t, then e, then a |
for ends with a colon. The repeated line sits four spaces in. for is lowercase. For with a capital F stops the program.
The next page keeps going while an answer stays True
This page already knows the values: three numbers, or the letters of tea. The next page is the while loop. It repeats while an answer stays True.
Say these yourself
- range(3) writes 0, then 1, then 2.
- range(1, 3) writes 1, then 2.
- "tea" writes t, then e, then a.
- print("done") runs once, after the letters.
- After range(3), cup still holds 2.
- The next page is the while loop.
Easy to misread
- Expecting range(3) to write 3
- Expecting range(1, 3) to write 3
- Expecting done on every pass
- Leaving out the colon after for
- Writing For with a capital F
Keep
for repeats the indented line once per value.
range(3) writes 0, 1, 2. The end number is not taken. Afterward cup still holds 2.
range(1, 3) writes 1, 2.
"tea" writes t, e, a. A line level with for runs once, after.
The next page is the while loop.
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top