While Loop & Flowcharts
The while loop repeats a block of code as long as a condition
remains True. It is ideal when you don't know in advance how many times the loop should
run. Flowcharts provide a visual way to design and understand loop algorithms before coding.
Learning Objectives
- 11.1.2.1 Write program code using a While loop
- 11.1.2.2 Implement a loop algorithm according to a flowchart
Conceptual Anchor
The Guard at the Door
A while loop is like a guard checking a condition before letting
you through the door again. Each time you finish the loop body, you return to the guard. If the
condition is still True, you go through again. If it's False, the guard stops you and the
program continues past the loop.
Rules & Theory
While Loop Syntax
# Basic pattern
while condition:
# body — runs while condition is True
# MUST modify something to eventually make condition False
# Simple counting
count = 1
while count <= 5:
print(count)
count += 1 # Without this → infinite loop!
# Output: 1 2 3 4 5 (each on a new line)Flowchart Structure
| Flowchart Shape | Meaning | Python Equivalent |
|---|---|---|
| Oval | Start / End | Beginning / End of program |
| Parallelogram | Input / Output | input() / print() |
| Rectangle | Process | Assignment, calculation |
| Diamond | Decision | while condition: |
| Arrow | Flow direction | Sequence of execution |
While Loop Flowchart Pattern
In a flowchart, a while loop always has: (1) Initialize a variable, (2) Diamond: check condition, (3) Yes → process body → loop back to diamond, (4) No → continue to next step.
Common While Loop Patterns
# Pattern 1: Counter-controlled
count = 0
while count < 10:
print(count)
count += 1
# Pattern 2: Sentinel value (user says "stop")
text = input("Enter text (or 'quit'): ")
while text != "quit":
print("You said:", text)
text = input("Enter text (or 'quit'): ")
# Pattern 3: Accumulator
total = 0
num = int(input("Enter number (0 to stop): "))
while num != 0:
total += num
num = int(input("Enter number (0 to stop): "))
print("Total:", total)
# Pattern 4: Input validation
age = int(input("Enter age (1-120): "))
while age < 1 or age > 120:
print("Invalid! Try again.")
age = int(input("Enter age (1-120): "))Worked Examples
1 Countdown Timer
count = 10
while count > 0:
print(count)
count -= 1
print("Launch!")
# Trace table:
# count | Output
# 10 | 10
# 9 | 9
# ...
# 1 | 1
# 0 | Launch!2 Guessing Game (Flowchart Implementation)
Flowchart: Start → Set secret=7 → Input guess → Is guess == secret? → No: Too high/low → Input guess again → Yes: "Correct!" → End
secret = 7
guess = int(input("Guess the number (1-10): "))
while guess != secret:
if guess > secret:
print("Too high!")
else:
print("Too low!")
guess = int(input("Try again: "))
print("Correct! 🎉")3 Sum of Digits
# Extract and sum each digit of a number
num = int(input("Enter a number: ")) # e.g., 347
total = 0
while num > 0:
digit = num % 10 # Get last digit
total += digit # Add to total
num = num // 10 # Remove last digit
print("Sum of digits:", total)
# Trace for 347:
# num | digit | total
# 347 | 7 | 7
# 34 | 4 | 11
# 3 | 3 | 14
# 0 | (stop)| 144 Password Checker with Attempt Limit
correct = "python123"
attempts = 3
while attempts > 0:
pw = input("Enter password: ")
if pw == correct:
print("Access granted!")
break
else:
attempts -= 1
print(f"Wrong! {attempts} attempts left.")
if attempts == 0:
print("Account locked!")Pitfalls & Common Errors
Infinite Loop
If the condition never becomes False, the loop runs forever. Always ensure the loop variable
changes inside the loop body. Press Ctrl+C to stop an infinite loop.
# BUG: count never changes!
count = 1
while count <= 5:
print(count)
# Missing: count += 1Off-by-One Error
while count < 5 runs 5 times (0,1,2,3,4). while count <= 5 runs 6 times
(0,1,2,3,4,5). Always trace the first and last iterations.
Sentinel Not Updated
If you use a sentinel value to exit, make sure the input is inside the loop, not just before it.
Pro-Tips for Exams
Loop Tracing Strategy
- Always draw a trace table with columns for each variable + output
- Check the condition BEFORE each iteration (including the first)
- Count the total number of iterations carefully
- For flowchart → code: map each diamond to a
whilecondition, each rectangle to a statement
Graded Tasks
What are the three essential parts of every while loop?
Draw a flowchart for a program that sums numbers entered by the user until they enter 0.
Write a program that asks the user for a positive integer and prints its factorial using a while loop.
Implement the following flowchart: Input a number → While number > 1 → If even: divide by 2 → If odd: multiply by 3 and add 1 → Print number → Count steps.
Trace the following code and write the output:
x = 100; while x > 1: x = x // 2; print(x)
Create a number guessing game where the computer picks a random number 1-100 and the user must guess it, receiving "higher" or "lower" hints. Count and display the number of attempts.
Self-Check Quiz
i = 0; while i < 3: i += 1break do inside a while loop?