Learning Goals
3 minBy the end of this lesson you can:
- Write a
whileloop with a clear stop condition. - Use a counter variable to repeat a block a known number of times.
- Use a Boolean flag to stop a loop when the user is finished.
Warm-Up
5 minYesterday's Rock-Paper-Scissors was fun — but to play three rounds, you had to run the program three times. That's the bit we'll fix today.
Quick predict-the-output puzzle. What does this print, and how many lines does it print in total?
n = 3 while n > 0: print("Round", n) n = n - 1 print("Game over")
Show the answer
Round 3 Round 2 Round 1 Game over
Four lines. Python checked n > 0 three times (each time it was true), then a fourth time when n was 0 — which is false, so the loop stopped and the script moved on to print("Game over").
while repeats a block of code as long as a Boolean condition is true. Pair it with a counter that ticks down (or up) each pass, and your program can run a section ten times — or a hundred — without copy-pasting a single line.
New Concept · Looping with while
12 minPart 1 · The shape of a while loop
A while loop looks almost identical to an if statement. The two big differences: it uses the word while, and Python runs the block again and again until the condition stops being true.
while CONDITION: do something do something else
Same colon, same 4-space indentation, same rule: every line that belongs inside the loop is indented by four spaces.
Part 2 · The counter pattern
The most common way to control a while loop is with a counter: a number you start at one value, check inside the condition, and change inside the loop body.
count = 1 while count <= 5: print("Hello number", count) count = count + 1
Read it like a recipe:
countstarts at1.- Is
count <= 5true? Yes — run the indented block. - The block prints, then nudges
countup by one. - Back to step 2. Eventually
countreaches6, the condition becomes false, and the loop stops.
+= 1 shortcutThe line count = count + 1 is so common that Python has a shortcut: count += 1. Both do the same thing. Use whichever you find clearer; we'll mix the two in this course.
Part 3 · The dreaded infinite loop
If you forget to change the counter inside the loop, the condition stays true forever and your program never ends. This is the infinite loop bug.
count = 1 while count <= 5: print("Stuck!")
If your terminal won't stop printing, press Ctrl + C on Windows / Linux, or Cmd + C on macOS. Python interrupts the loop and gives you the prompt back. In online-python.com, hit the red Stop button. Every Python coder makes infinite loops by mistake — Ctrl + C is your friend.
Part 4 · Stopping a loop with a Boolean flag
Counters work brilliantly when you know up front how many times to repeat. But sometimes you want to keep going until the user says stop — there's no number to count down. That's a job for a Boolean flag.
running = True while running: answer = input("Type 'stop' to end, anything else to continue: ") if answer == "stop": running = False else: print("Still going…") print("Loop is over.")
Two ideas at work: the loop runs while running is true, and somewhere inside the body, an if sets running to False when it's time to stop.
Part 5 · while True: + a flag
Some people prefer writing while True: and using if to flip the flag — same idea, slightly different shape. Either pattern is fine in Level 1. Stick with the flag version for now; it's easier to reason about.
Worked Example · A Spend Tracker
12 minDaniel Tan is saving for a new bike. Each week he wants to type in everything he spent and have Python total it up. We'll build a tiny spend tracker that keeps asking for amounts until he types done. Save this as spend_tracker.py.
Code
# spend_tracker.py — add spending amounts until the user is finished total = 0.0 item_count = 0 done = False while not done: answer = input("RM amount (or 'done' to finish)? ") if answer == "done": done = True else: amount = float(answer) total = total + amount item_count = item_count + 1 print(" Added RM", amount, "· running total: RM", total) print() print("Spending done — you logged", item_count, "items.") print("Final total: RM", total)
One sample run (lines you type are bold):
Output
RM amount (or 'done' to finish)? <strong>5.50</strong> Added RM 5.5 · running total: RM 5.5 RM amount (or 'done' to finish)? <strong>2.00</strong> Added RM 2.0 · running total: RM 7.5 RM amount (or 'done' to finish)? <strong>8.50</strong> Added RM 8.5 · running total: RM 16.0 RM amount (or 'done' to finish)? <strong>done</strong> Spending done — you logged 3 items. Final total: RM 16.0
Reading the loop slowly
totalanditem_countare accumulators — they start at zero and grow inside the loop.doneis a Boolean flag. The loop runs while it is not done — a really natural English reading thanks tonotfrom PY-L1-10.- Inside the loop, exactly one of two branches runs: either we set
done = Trueto leave next time round, or we update the running total. - When the loop finishes (because
not doneis now false), Python falls through to the final twoprintlines.
Try It Yourself
13 minRun each task with at least two different inputs before moving on.
Ask the user for a number n. Print the numbers 1, 2, 3, …, n on separate lines using a while loop.
Hint
n = int(input("Count up to? ")) i = 1 while i <= n: print(i) i = i + 1
Ask for a number n. Calculate 1 + 2 + … + n using a counter and an accumulator. Print the result.
Hint
n = int(input("Sum up to? ")) i = 1 total = 0 while i <= n: total = total + i i = i + 1 print("Sum is", total)
Two variables that change each pass: total grows, i ticks up. Forgetting i = i + 1 is the most common bug — it gives you an infinite loop printing the same total.
Keep asking the user for numbers until they type "done". Track the largest number seen so far in a variable biggest, then print it at the end.
Hint
Start biggest very small (or set it from the first valid input). Compare each new number using if value > biggest:.
biggest = 0 done = False while not done: answer = input("A number (or 'done')? ") if answer == "done": done = True else: value = int(answer) if value > biggest: biggest = value print("Biggest was", biggest)
Mini-Challenge · RPS, Again and Again
8 minTime to give Rock, Paper, Scissors the power it deserved all along. Wrap last lesson's game in a while loop so it plays many rounds in a single run.
Your file must:
- Start a fresh file called
rps_loop.pyandimport randomat the top. - Keep two counters:
player_scoreandcomputer_score, both starting at0. - Use a Boolean flag
playing = Trueto drive awhile playing:loop. - Inside the loop:
- Ask
player = input("rock, paper, scissors or 'quit'? "). - If
player == "quit", setplaying = Falseand skip the rest of this round. - Otherwise, roll the computer's move with
random.randint(1, 3)and map it torock/paper/scissorsas in PY-L1-11. - Compute
tieandplayer_winsBooleans (same rules as before). - Update the scores: add 1 to
player_scorewhenplayer_wins; add 1 tocomputer_scorewhen neithertienorplayer_wins. - Print this round's result.
- Ask
- After the loop ends, print the final scoreboard.
Stretch goal. Reject bad moves: if player isn't one of "rock", "paper", "scissors" or "quit", print "That's not a real move — try again." and don't change the scores. The loop continues to the next iteration normally.
Show one possible solution
# rps_loop.py — Rock, Paper, Scissors with a scoreboard import random player_score = 0 computer_score = 0 playing = True while playing: player = input("rock, paper, scissors or 'quit'? ") if player == "quit": playing = False else: # Computer's roll n = random.randint(1, 3) if n == 1: computer = "rock" elif n == 2: computer = "paper" else: computer = "scissors" # Result Booleans tie = player == computer player_wins = (player == "rock" and computer == "scissors") \ or (player == "paper" and computer == "rock") \ or (player == "scissors" and computer == "paper") # Update scores if player_wins: player_score = player_score + 1 print("🎉 You win this round! (Computer played", computer + ")") elif tie: print("🤝 Tie — both picked", player) else: computer_score = computer_score + 1 print("🤖 Computer wins this round with", computer) print() print("Final scoreboard") print("You: ", player_score) print("Computer: ", computer_score)
If you tried the stretch and your "bad move" branch also rolls the computer's move, you'll see the computer "playing" against nothing. Move the random roll inside a valid_move check, so the computer only plays when the player did.
Recap
3 minOne small keyword unlocked a huge new ability. With while, a counter, and a stop condition, our programs can do a job ten times, or until the user says enough — without a single copy-pasted line. Watch the counter every time: forgetting to update it is how you build an infinite loop.
Vocabulary Card
- loop
- A block of code that runs more than once.
- while loop
- Repeats its block as long as a Boolean condition is true.
- counter
- A variable that changes each pass — usually
+ 1or- 1. - accumulator
- A variable that grows each pass, like a running total.
- infinite loop
- A loop whose condition never becomes false — stop it with Ctrl + C.
Homework
4 minCreate a new file called times_table.py — a tidy multiplication-table printer.
Rules:
- Ask the user for a number,
base, and convert it withint(). - Use a
whileloop and a counterithat starts at1to print the times table from1 × baseto12 × base— one line per row, like3 × 7 = 21. - After the loop, print one summary line:
"That's the 12-times table for 7"(with the user's number). - Stretch. Also keep a running
totalof every product, and print it at the end:"All twelve products add up to: 546"(for base 7).
Bring times_table.py to next lesson — we'll explore an even tidier loop style (the for loop) and see how the same job looks with that.
Sample · times_table.py
# times_table.py — print a 1-to-12 times table base = int(input("Which number's times table? ")) i = 1 total = 0 while i <= 12: product = i * base print(i, "×", base, "=", product) total = total + product i = i + 1 print() print("That's the 12-times table for", base) print("All twelve products add up to:", total)
Your message wording and the order of statements can vary. The two non-negotiables are: a counter i that stops the loop at 12, and i = i + 1 (or i += 1) inside the loop so the counter actually changes.