These are the notes for Python episode 7. Last episode, the program learned to choose with if. Today it learns to repeat. You will learn the while loop and its four parts, the infinite loop (and why the online compiler says Time Limit Exceeded), accumulators, off-by-one errors, asking the user again until the input is right, while True with break, continue, and Python's unusual while ... else. 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: copy-paste breaks
Raju's chai stall is so busy that every customer gets a token number. We write a program that prints the tokens, one print per customer, by copying the line and changing the number:
print("Token 1")
print("Token 2")
print("Token 3")
print("Token 3")
print("Token 5")
Output:
Token 1
Token 2
Token 3
Token 3
Token 5
Token 3 twice, and no Token 4: we pasted a line and forgot to change the number. And on Saturday there are 100 customers: 100 lines, 100 chances for a typo, and if Raju wants "Ticket" instead of "Token", 100 edits.
Why it failed: we are doing the computer's job by hand. Repeating work is exactly what computers are good at; we need a way to say "do this again, and again, until we're done".
The while loop
Real-life example: filling a water tank with a bucket.
| Filling the tank | In Python |
|---|---|
| Before every bucket, look: is the tank full yet? | while token <= 5: checks a condition before every round |
| Not full? Pour one bucket (the same job each time) | the indented body of the loop runs |
| Every bucket raises the water level | token += 1 changes something each round |
| Full: stop pouring and do something else | the condition is False, so Python runs the line after the loop |
A loop is code that runs a block again and again. The while loop repeats its block as long as its condition is True.
token = 1
while token <= 5:
print("Token", token)
token += 1
print("Shop closed")
Output:
Token 1
Token 2
Token 3
Token 4
Token 5
Shop closed
Just like if, the while line ends with a colon and the body is indented by 4 spaces. print("Shop closed") is back at the left edge, so it is after the loop and runs once.
For 100 customers, change one number: while token <= 100: prints Token 1 to Token 100 from the same four lines. Each trip around the loop is called an iteration.
How a while loop runs
┌──────────────────────────────┐
▼ │
check: token <= 5 ? ── True ──► body: print, token += 1
│
False
▼
the line after the loop
- Python checks the condition.
- If it is
True, it runs the body, then goes back up and checks again. - The moment it is
False, it skips the body and carries on after the loop.
The check happens before every iteration (including the first: if the condition is False at the start, the body runs zero times).
The four parts of a counting loop
| Part | Code | Job |
|---|---|---|
| Start | token = 1 |
set up the counter before the loop |
| Check | while token <= 5: |
decide whether to do another round |
| Body | print("Token", token) |
the work to repeat |
| Change | token += 1 |
move the loop towards its end |
Forget one, and things go wrong.
The infinite loop trap
Real-life example: Priya saves ₹50 every day for a week. How much will she have? But we forget to move to the next day:
day = 1
total = 0
while day <= 7:
total += 50
print("Saved:", total)
Result in the SyntaxPilot compiler: nothing is printed, and after 8 seconds the status shows Time Limit Exceeded.
day stays 1 forever. "Is 1 ≤ 7? Yes. Add 50. Is 1 ≤ 7? Yes..." A loop whose condition never becomes False is an infinite loop. On your own computer it runs until you stop it with Ctrl + C; online compilers stop it after a time limit.
The fix is the missing change:
day = 1
total = 0
while day <= 7:
total += 50
day += 1
print("Saved: Rs", total)
Output: Saved: Rs 350
Accumulators
total starts at 0 before the loop, and every iteration adds to it. A variable that collects a running total like this is an accumulator. The same pattern counts things (count += 1), adds scores, builds totals.
Off-by-one errors
day = 1
while day < 7:
print("Day", day)
day += 1
Output:
Day 1
Day 2
Day 3
Day 4
Day 5
Day 6
Only six days: < 7 stops before 7. Being wrong by exactly one round is so common it has a name: an off-by-one error. while day <= 7: prints Day 1 to Day 7. Always check the first and the last value your loop uses.
Ask until it's right
Real-life example: Raju's stall has free Wi-Fi; the password is chai123. With last episode's if, we give one more chance:
password = input("Password: ")
if password != "chai123":
password = input("Wrong! Try again: ")
print("Welcome to Raju's Wi-Fi")
Input (three lines): chai, Chai123, chai123 → output:
Password: Wrong! Try again: Welcome to Raju's Wi-Fi
(The compiler doesn't echo typed input, so the prompts sit on one line.) Two wrong passwords, and the customer is still welcomed! An if asks its question once; the second answer is never checked.
Change one word, if → while:
password = input("Password: ")
while password != "chai123":
password = input("Wrong! Try again: ")
print("Welcome to Raju's Wi-Fi")
Same input → output:
Password: Wrong! Try again: Wrong! Try again: Welcome to Raju's Wi-Fi
It asks as many times as it takes. Here the "change" part of the loop is the user typing a new password. if asks once, while asks until.
EOFError: the input ran out
Run the same program with only chai in the input box:
Traceback (most recent call last):
File "main.py", line 3, in <module>
password = input("Wrong! Try again: ")
EOFError: EOF when reading a line
EOF means end of file: input() asked for another line and there was nothing left to read. On your own computer the program would simply wait for you to type. In an online compiler, put every answer in the input box, one per line, before pressing Run.
while True and break
Real-life example: the waiter writing your order. He doesn't know how many dishes you'll order, so he keeps writing until you say "that's all".
| At the table | In Python |
|---|---|
| The waiter keeps writing | while True: repeats with no condition to stop it |
| "One masala dosa" goes on the bill | the body: total += int(item) |
| "That's all": he stops | break jumps out of the loop immediately |
total = 0
while True:
item = input("Price (or done): ")
if item == "done":
break
total += int(item)
print("Bill: Rs", total)
Input: 12, 15, 40, done → output:
Price (or done): Price (or done): Price (or done): Price (or done): Bill: Rs 67
while True: is a loop whose condition is always True; the only way out is break. break ends the loop at once and Python continues with the first line after it.
A bad entry crashes the bill
Input: 12, fifteen, 40, done →
Traceback (most recent call last):
File "main.py", line 6, in <module>
total += int(item)
~~~^^^^^^
ValueError: invalid literal for int() with base 10: 'fifteen'
int() can only convert digits. One bad entry and the whole bill is lost.
continue: skip this round
total = 0
while True:
item = input("Price (or done): ")
if item == "done":
break
if not item.isdigit():
print("Skipping", item)
continue
total += int(item)
print("Bill: Rs", total)
Input: 12, fifteen, 40, done → output:
Price (or done): Price (or done): Skipping fifteen
Price (or done): Price (or done): Bill: Rs 52
item.isdigit()is a string method that returnsTruewhen every character is a digit0-9(and the text is not empty)."40".isdigit()isTrue,"fifteen".isdigit()isFalse,"-5".isdigit()isFalse.continueskips the rest of the body and jumps straight back to the check for the next round.
break |
continue |
|
|---|---|---|
| What it does | leaves the loop completely | skips the rest of this round only |
| What runs next | the first line after the loop | the loop's check, then the next round |
while ... else: did we break?
Real-life example: the ATM. The right PIN gives cash; a wrong PIN lets you try again, but only 3 times; after 3 wrong PINs the card is blocked. The loop can end two ways (success with break, or running out of tries), and we need to know which one happened.
attempts = 0
while attempts < 3:
pin = input("PIN: ")
attempts += 1
if pin == "4321":
print("Cash dispensed")
break
print("Wrong PIN. Tries left:", 3 - attempts)
else:
print("Card blocked")
Input 1111, 4321 →
PIN: Wrong PIN. Tries left: 2
PIN: Cash dispensed
Input 1111, 2222, 3333 →
PIN: Wrong PIN. Tries left: 2
PIN: Wrong PIN. Tries left: 1
PIN: Wrong PIN. Tries left: 0
Card blocked
An else lined up with a while runs only if the loop ended normally, i.e. its condition became False without a break. Few languages have this; in Python it saves you a separate "success" flag.
Summary of loop control
| Tool | Meaning |
|---|---|
while True: |
repeat until something breaks out |
break |
leave the loop now |
continue |
skip the rest of this round, go to the next check |
while ... else: |
else runs only if there was no break |
A
while Truewith nobreakthat can actually happen is an infinite loop again.
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
while day <= 7: without day += 1 |
Time Limit Exceeded (runs forever) | nothing changes, the check stays True |
change the counter inside the loop |
while day < 7: to get 7 days |
no error, only 6 days | off by one: < stops early |
while day <= 7: |
| too few lines in the input box | EOFError: EOF when reading a line |
input() ran out of input |
type every answer, one per line |
int("fifteen") |
ValueError: invalid literal for int() with base 10: 'fifteen' |
int() needs digits |
check isdigit() first, continue |
forgetting the colon: while x < 5 |
SyntaxError: expected ':' |
same rule as if |
while x < 5: |
| body not indented | IndentationError: expected an indented block after 'while' statement on line 2 |
Python can't tell what to repeat | indent the body 4 spaces |
Mini project: guess the number
The computer keeps a secret number, 37. Keep asking while the guess is wrong, give a hint each time, and count the tries.
# Mini project: guess the number
secret = 37
tries = 0
guess = 0
while guess != secret:
guess = int(input("Guess (1-100): "))
tries += 1
if guess < secret:
print(guess, "is too low")
elif guess > secret:
print(guess, "is too high")
print(f"Got it in {tries} tries!")
Input 50, 25, 37 → output:
Guess (1-100): 50 is too high
Guess (1-100): 25 is too low
Guess (1-100): Got it in 3 tries!
guess starts at 0 so the first check is True and the loop starts. In a later episode Python will pick a random secret with the random module.
Extend it: game over after 7 tries, using while ... else.
Solution
secret = 37
tries = 0
while tries < 7:
guess = int(input("Guess (1-100): "))
tries += 1
if guess == secret:
print(f"Got it in {tries} tries!")
break
elif guess < secret:
print(guess, "is too low")
else:
print(guess, "is too high")
else:
print("Game over! The number was", secret)
Practice
1. New Year countdown. Print 10 down to 1, then Happy New Year!
Solution
n = 10
while n >= 1:
print(n)
n -= 1
print("Happy New Year!")
2. Count the digits of a number (e.g. 2026 has 4 digits) without converting it to text.
Solution
n = int(input("Number: "))
digits = 0
while n > 0:
n = n // 10
digits += 1
print("Digits:", digits)
Input 2026 → Number: Digits: 4. n // 10 drops the last digit each round (episode 4). Bonus: what does it print for 0, and how would you fix it?
3. Valid age. Keep asking for an age until it is between 1 and 120.
Solution
age = int(input("Age: "))
while age < 1 or age > 120:
age = int(input("Age must be 1 to 120. Again: "))
print("Age saved:", age)
4. Sum until zero. Add numbers until the user types 0, then print the total.
Solution
total = 0
while True:
n = int(input("Number (0 to stop): "))
if n == 0:
break
total += n
print("Total:", total)
5. Multiplication table with while. Print the table of 9 from 9 × 1 to 9 × 10.
Solution
n = 1
while n <= 10:
print(f"9 x {n} = {9 * n}")
n += 1
Quick quiz
What does this print?
n = 1
while n < 20:
n = n * 3
print(n)
A) 9 B) 20 C) 27 D) 81
Answer
C) 27. n goes 1 → 3 → 9 → 27. At 9 the check 9 < 20 is still True, so the loop runs once more. At 27 the check is False, the loop stops and 27 is printed. The check happens before each round, never in the middle.
Interview questions
- What is the difference between
whileandif? Both check a condition, butifruns its block at most once, whilewhilekeeps running its block as long as the condition staysTrue. - What is an infinite loop and how do you avoid one? A loop whose condition never becomes
False. Make sure something in the body moves the loop towards its end (a counter that changes, new input, a reachablebreak). - What is the difference between
breakandcontinue?breakexits the loop entirely;continueskips the rest of the current iteration and goes to the next check. - When does the
elseof awhileloop run? Only when the loop ends because its condition becameFalse, i.e. without abreak. It does not run if the loop was left withbreak. - Does Python have a
do-whileloop? No. The usual equivalent iswhile True:with the body first and anif ...: breakat the end, which guarantees the body runs at least once. - What is an off-by-one error? A loop that runs one time too many or too few, usually from
<vs<=or a wrong start value.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Loop | Code that runs a block again and again | while token <= 5: |
while loop |
Repeats its block as long as its condition is True |
while password != "chai123": |
| Body | The indented block a loop repeats | print("Token", token) |
| Iteration | One trip around the loop | the round where token is 3 |
| Counter | A variable that counts the rounds | token, day, attempts |
| Start / check / change | The parts of a counting loop besides the body | token = 1 / token <= 5 / token += 1 |
| Infinite loop | A loop whose condition never becomes False |
while day <= 7: with no day += 1 |
| Time Limit Exceeded | An online compiler stopped a program that ran too long | the infinite savings loop |
| Ctrl + C | Keyboard shortcut that stops a running program in a terminal | stopping an infinite loop |
| Accumulator | A variable that collects a running total | total += 50 |
| Off-by-one error | A loop that runs one round too many or too few | while day < 7: gives 6 days |
EOFError |
input() found no more input to read (EOF = end of file) |
too few lines in the input box |
while True |
A loop with no stopping condition; needs a break |
the waiter's order loop |
break |
Leaves the loop immediately | if item == "done": break |
continue |
Skips the rest of this round, goes to the next check | skipping fifteen |
isdigit() |
String method: True if every character is a digit 0-9 |
"40".isdigit() → True |
ValueError |
A value of the right type but wrong content | int("fifteen") |
while ... else |
else runs only if the loop ended without break |
Card blocked |
| Flag | A True/False variable that remembers something happened | found = True |
Summary
while condition:repeats its indented body as long as the condition isTrue; the check happens before every round.- A counting loop has four parts: start, check, body, change. Forget the change and you get an infinite loop (Time Limit Exceeded online, Ctrl + C at home).
- An accumulator starts at 0 before the loop and grows each round:
total += x. - Check the first and last round to avoid off-by-one errors.
ifasks once,whileasks until: perfect for re-asking for input.while True+breakfor "until the user says stop";continueskips one round; a loop'selseruns only if there was nobreak.- Online compilers need every input line typed in advance, or you get
EOFError.
Next episode: for loops and range().