These are the notes for Python episode 8. Last episode, the while loop made programs repeat, but we had to manage a counter ourselves, and one forgotten line froze the program. Today Python manages it for us. You will learn the for loop over text, counting with for + if, range() with start, stop and step, why range(1, 10) stops at 9, countdowns, print(..., end=" "), break, continue and for ... else, the _ variable, and when to choose for or while. Every example below runs as-is in the SyntaxPilot compiler (type every input line in the input box before you press Run), with its real output from Python 3.13.
The problem: a while loop that crashes
Lots of real programs look at text one letter at a time: checking a PNR, counting vowels, hiding a password. Let's print the word CHAI, one letter per line. From episode 5, every letter sits in a numbered seat starting at 0 (word[0] is C), so we walk the seat numbers with a while loop:
word = "CHAI"
i = 0
while i <= len(word):
print(word[i])
i += 1
Output:
C
H
A
I
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(word[i])
~~~~^^^
IndexError: string index out of range
len("CHAI") is 4, but the seats are 0 to 3. i <= 4 asks for seat 4, which doesn't exist: an off-by-one error. An IndexError means you asked for a position that isn't there.
Why it failed: four bits of bookkeeping (start, check, change, and the index in
[ ]) just to say "give me each letter", and one of them was off by one.
The for loop
Real-life example: the ticket checker (TTE) walks the coach. He doesn't count seat numbers; he just goes from the first passenger to the last.
| In the train | In Python |
|---|---|
| The coach: passengers in order | "CHAI": a sequence of letters in order |
| "This passenger", one at a time | the loop variable letter holds the current item |
| Check the ticket, the same job each time | the body runs once per item |
| End of the coach: he simply stops | the loop ends after the last item, no counter needed |
for letter in "CHAI":
print(letter)
Output:
C
H
A
I
Read it out loud: "for each letter in CHAI, print the letter". The for loop runs its body once for each item of a sequence, putting the item in the loop variable. No start, no check, no change, no index, no off-by-one.
Anything you can loop over like this is an iterable. Text (a string) is iterable; lists, tuples, sets, dictionaries and files (later episodes) are too.
for + if + accumulator: counting vowels
word = input("Word: ")
vowels = 0
for ch in word.lower():
if ch in "aeiou":
vowels += 1
print("Vowels:", vowels)
| Input | Output |
|---|---|
Banana |
Word: Vowels: 3 |
Rhythm |
Word: Vowels: 0 |
word.lower()makesAcount likea.ch in "aeiou"(episode 5) asks: is this one letter inside the textaeiou?vowelsis an accumulator that starts at 0.
A for loop, an if and an accumulator: that combination solves a huge number of counting problems.
range(): sequences of numbers
The table of 7 needs the numbers 1 to 10, but a for loop needs a sequence. range() is a built-in function that makes a sequence of whole numbers.
for i in range(5):
print("Token", i)
Output:
Token 0
Token 1
Token 2
Token 3
Token 4
Five numbers, but starting from 0 and stopping before 5, just like string seats.
start, stop, step
Real-life example: reading a book up to a bookmark.
| Reading a book | In Python | Rule |
|---|---|---|
| Start on page 1 | range(1, ...) |
start: included (default 0) |
| Bookmark on page 11: stop, don't read it | range(1, 11) → 1 … 10 |
stop: never included |
| Read every 2nd page | range(1, 11, 2) → 1, 3, 5, 7, 9 |
step: how far to jump (default 1) |
| Call | Numbers |
|---|---|
range(5) |
0, 1, 2, 3, 4 |
range(1, 6) |
1, 2, 3, 4, 5 |
range(2, 21, 2) |
2, 4, 6, …, 20 |
range(10, 0, -1) |
10, 9, …, 1 |
range(10, 0) |
nothing (empty) |
The table of 7, and an off-by-one
for n in range(1, 10):
print(7, "x", n, "=", 7 * n)
Output (9 lines): 7 x 1 = 7 … 7 x 9 = 63. 7 × 10 is missing: the stop is never included.
for n in range(1, 11):
print(f"7 x {n} = {7 * n}")
Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
To count from
atob(both included), writerange(a, b + 1).
A step, and end=" "
for n in range(2, 21, 2):
print(n, end=" ")
Output: 2 4 6 8 10 12 14 16 18 20
Normally print ends with a new line. end=" " tells print to end with a space instead, so everything stays on one line.
Counting down
for n in range(10, 0):
print(n, end=" ")
print("Lift off!")
Output: Lift off! — no numbers and no error. range counts up by default, and you can't count up from 10 to 0, so the range is empty and the loop runs zero times.
for n in range(10, 0, -1):
print(n, end=" ")
print("Lift off!")
Output: 10 9 8 7 6 5 4 3 2 1 Lift off! — a negative step counts down. The stop (0) is still not included.
Adding 1 to 100
total = 0
for n in range(1, 101):
total += n
print("Sum:", total)
Output: Sum: 5050 — the same accumulator pattern as with while. (The famous story: a teacher asked a class to add 1 to 100 to keep them busy; young Carl Friedrich Gauss paired 1 + 100, 2 + 99, … into 50 pairs of 101 = 5050.)
Two TypeErrors
for i in 5:
print("Hello")
Traceback (most recent call last):
File "main.py", line 1, in <module>
for i in 5:
^
TypeError: 'int' object is not iterable
A number is not a sequence: the ticket checker needs a coach to walk. Use for i in range(5):.
cups = 2.5
for i in range(cups):
print("Chai")
Traceback (most recent call last):
File "main.py", line 2, in <module>
for i in range(cups):
~~~~~^^^^^^
TypeError: 'float' object cannot be interpreted as an integer
range() only takes whole numbers (int). Convert with int() or rethink the problem.
break, continue and for ... else
Real-life example: a train PNR is 10 digits, and people often type the letter O instead of zero. Check each character; at the first bad one, stop.
pnr = input("PNR: ")
for ch in pnr:
if not ch.isdigit():
print("Invalid character:", ch)
break
else:
print("PNR looks valid")
| Input | Output |
|---|---|
2468135790 |
PNR: PNR looks valid |
24681O5790 |
PNR: Invalid character: O |
break, continue and else work exactly like with while: the else of a for runs only if the loop finished without break.
for n in range(1, 11):
if n % 3 == 0:
continue
print(n, end=" ")
Output: 1 2 4 5 7 8 10 — continue skipped 3, 6 and 9 and the loop carried on.
_: when you don't need the number
for _ in range(3):
print("Hip hip hooray!")
Output:
Hip hip hooray!
Hip hip hooray!
Hip hip hooray!
_ is a normal variable name, but by convention it says "I don't need this value".
for or while?
Use for when… |
Use while when… |
|---|---|
| you know what to go through: each letter, a range of numbers, (soon) each item in a list | you repeat until something happens and can't know the number of rounds in advance |
for ch in pnr: / for n in range(1, 11): |
while password != "chai123": / while guess != secret: |
Most loops you will ever write are for loops.
A detail: the loop variable still exists after a for loop, holding the last value:
for i in range(3):
print(i)
print("After the loop, i is", i)
Output: 0, 1, 2, then After the loop, i is 2.
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
while i <= len(word): word[i] |
IndexError: string index out of range |
the last seat is len - 1 |
for letter in word: |
range(1, 10) for 1 to 10 |
no error, stops at 9 | stop is never included | range(1, 11) |
for i in 5: |
TypeError: 'int' object is not iterable |
a number is not a sequence | for i in range(5): |
range(2.5) |
TypeError: 'float' object cannot be interpreted as an integer |
whole numbers only | range(int(x)) |
range(10, 0) to count down |
no error, nothing printed | empty range, counts up by default | range(10, 0, -1) |
forgetting the colon: for ch in word |
SyntaxError: expected ':' |
same rule as if/while |
for ch in word: |
Mini project: Raju's weekly sales report
Ask for 7 days of sales; print the total, the average (2 decimal places) and the best day.
# Mini project: Raju's weekly sales report
total = 0
best = 0
best_day = 0
for day in range(1, 8):
sales = int(input(f"Day {day} sales: "))
total += sales
if sales > best:
best = sales
best_day = day
print()
print(f"Total: Rs {total}")
print(f"Average: Rs {total / 7:.2f}")
print(f"Best: day {best_day} (Rs {best})")
Input 1200, 950, 1430, 1100, 2150, 2600, 1800 → output:
Day 1 sales: Day 2 sales: Day 3 sales: Day 4 sales: Day 5 sales: Day 6 sales: Day 7 sales:
Total: Rs 11230
Average: Rs 1604.29
Best: day 6 (Rs 2600)
- Best so far: keep the biggest value seen so far and replace it whenever something beats it.
{total / 7:.2f}inside an f-string rounds to 2 decimal places (f= fixed-point number).
Extend it: add the worst day.
Solution
Add worst = 10**9 and worst_day = 0 before the loop, and inside it:
if sales < worst:
worst = sales
worst_day = day
then print(f"Worst: day {worst_day} (Rs {worst})"). With the same input: Worst: day 2 (Rs 950). (Starting worst at a huge number makes sure day 1 always replaces it.)
Practice
1. Table of any number the user types.
Solution
n = int(input("Table of: "))
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
2. Factorial. 5! = 5 × 4 × 3 × 2 × 1 = 120.
Solution
n = int(input("n: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print(f"{n}! = {fact}")
Input 5 → n: 5! = 120. A product accumulator starts at 1, not 0.
3. Reverse a word with a for loop.
Solution
word = input("Word: ")
rev = ""
for ch in word:
rev = ch + rev
print(rev)
Input chai → Word: iahc. Each new letter goes in front. (The shortcut is word[::-1] from episode 5.)
4. Sum of digits of a number typed as text.
Solution
num = input("Number: ")
total = 0
for ch in num:
total += int(ch)
print("Digit sum:", total)
Input 2026 → Number: Digit sum: 10.
5. Odd numbers from 1 to 19 on one line, using a step.
Solution
for n in range(1, 20, 2):
print(n, end=" ")
Output: 1 3 5 7 9 11 13 15 17 19
Quick quiz
What does this print?
for i in range(1, 10, 3):
print(i, end=" ")
A) 1 4 7 B) 1 4 7 10 C) 0 3 6 9 D) 1 2 3
Answer
A) 1 4 7. Start at 1, jump by 3: 1, 4, 7. The next would be 10, but the stop (10) is never included.
Interview questions
- What does
range(5)return? Arangeobject: a lazy sequence of the numbers 0, 1, 2, 3, 4. It doesn't build all the numbers in memory at once, sorange(1_000_000)is cheap.list(range(5))shows[0, 1, 2, 3, 4]. - Why is the stop of
rangeexcluded? So thatrange(n)has exactlynnumbers and lines up with indexes 0 … n-1 (range(len(word))), and sorange(a, b)andrange(b, c)join with no gap or overlap. - What is an iterable? Any object you can loop over with
for: strings, ranges, lists, tuples, sets, dictionaries, files. - When does the
elseof aforloop run? When the loop has gone through every item without hittingbreak. Typical use: searching ("not found" goes in theelse). forvswhile?forgoes through a known sequence;whilerepeats until a condition changes when the number of rounds isn't known in advance.- What is
_infor _ in range(3)? A normal variable name used by convention for a value you won't use.
Glossary
| Term | Meaning | Example |
|---|---|---|
for loop |
Runs its body once for each item of a sequence | for letter in "CHAI": |
| Sequence | Things in a fixed order | "CHAI", range(5) |
| Iterable | Anything a for loop can go through |
a string, a range |
| Loop variable | The variable that holds the current item | letter, n, ch |
| Body | The indented block run once per item | print(letter) |
IndexError |
You asked for a position that doesn't exist | "CHAI"[4] |
| Off-by-one error | One round too many or too few | range(1, 10) for 1 to 10 |
range() |
Built-in that makes a sequence of whole numbers | range(1, 11) |
| Start | The first number of a range (included, default 0) | the 1 in range(1, 11) |
| Stop | Where a range ends (never included) | the 11 in range(1, 11) |
| Step | How far a range jumps each time (default 1) | the 2 in range(2, 21, 2) |
| Negative step | Makes a range count down | range(10, 0, -1) |
| Empty range | A range with no numbers; the loop runs zero times | range(10, 0) |
end= |
What print puts after its output (default a new line) |
print(n, end=" ") |
| Accumulator | A variable that collects a total or count in a loop | vowels += 1 |
TypeError |
An operation got the wrong type of value | for i in 5: |
for ... else |
else runs only if the loop didn't break |
PNR looks valid |
_ |
Variable name for "I don't need this value" | for _ in range(3): |
| Best so far | Keep the largest value seen so far, replace when beaten | if sales > best: |
:.2f |
f-string format: 2 decimal places | f"{1604.2857:.2f}" → 1604.29 |
Summary
for x in sequence:runs the body once per item; no counter to forget, no index to get wrong.- Strings are iterable:
for ch in word:.for+if+ an accumulator counts things. range(stop)starts at 0;range(start, stop, step); the stop is never included; to go fromatob, userange(a, b + 1).- A negative step counts down;
range(10, 0)is empty and runs zero times. print(x, end=" ")stays on the same line.break,continueandfor ... elsework as withwhile;_marks an unused loop variable.- Known sequence →
for. Repeat until something happens →while.
Next episode: nested loops and patterns.