While Loops
1784 words
9 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# While Loops > **Why read this?** The real power of computers is repetition — doing something millions of times without getting bored. While loops let you repeat code as long as a condition is true.

While Loops
Why read this? The real power of computers is repetition — doing something millions of times without getting bored. While loops let you repeat code as long as a condition is true. They're the foundation of everything from calculating compound interest to processing every line of a file.
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Write
whileloops that repeat code based on a condition - Avoid and fix infinite loops
- Use accumulator patterns (sum, product, count)
- Implement sentinel-controlled loops (repeat until a signal value)
- Choose between
whileandforloops
📋 Prerequisites
- Conditionals — if/elif/else — Loop conditions use boolean expressions.
- Variables & Data Types — Updating variables inside loops.
📖 Core Content
9.1 What Problem Do While Loops Solve?
Intuition: "Keep pouring water until the glass is full." "Keep asking for a password until it's correct." "Keep dividing the number until you reach zero." While loops handle ANY repeated action where you don't know in advance how many repetitions you need.
9.2 The while Loop — Basic Structure
python# runnable count = 1 while count <= 5: print("Count:", count) count += 1 # CRITICAL: update the variable! print("Loop ended!")
Output:
pseudoCount: 1 Count: 2 Count: 3 Count: 4 Count: 5 Loop ended!
How it works:
- Check
count <= 5→ True, enter loop - Print count (1), then
count += 1(count becomes 2) - Back to top, check again:
2 <= 5→ True - ... repeat until count becomes 6
6 <= 5→ False, exit loop (Diagram)
9.3 The Infinite Loop — and How to Avoid It
What happens if you forget to update the variable?
python# runnable - CAUTION: This would run forever! # count = 1 # while count <= 5: # print("Hello") # count NEVER changes! # Run with caution - press Ctrl+C to stop # Instead, always ensure the condition can become False: count = 1 while count <= 5: print("Hello", count) count += 1 # This line prevents infinity
If you run an infinite loop in Repl.it or your IDE:
- Ctrl+C (or ⌘+C on Mac) interrupts the program
- Close the terminal window
- In Repl.it, click the Stop button
9.4 Sentinel-Controlled Loops
A sentinel is a special value that signals "stop."
python# runnable total = 0 count = 0 print("Enter numbers to sum. Enter -1 to stop.") num = float(input("Enter a number: ")) while num != -1: # -1 is the sentinel total += num count += 1 num = float(input("Enter a number: ")) if count > 0: print(f"Total: {total}") print(f"Average: {total/count:.2f}") else: print("No numbers entered.")
9.5 Worked Example 1: Factorial
n!=n×(n−1)×(n−2)×...×1python# runnable n = int(input("Enter n: ")) factorial = 1 i = 1 while i <= n: factorial *= i # same as: factorial = factorial * i i += 1 print(f"{n}! = {factorial}")
Output (for n=5):
pseudoEnter n: 5 5! = 120
Tracing the loop (n=5):
| Iteration | i | factorial |
|---|---|---|
| Start | 1 | 1 |
| 1 | 1→2 | 1*1 = 1 |
| 2 | 2→3 | 1*2 = 2 |
| 3 | 3→4 | 2*3 = 6 |
| 4 | 4→5 | 6*4 = 24 |
| 5 | 5→6 | 24*5 = 120 |
| Exit | 6 (not ≤5) | 120 |
9.6 Worked Example 2: Sum of Digits
python# runnable num = int(input("Enter a number: ")) original = num sum_digits = 0 while num > 0: digit = num % 10 # get last digit sum_digits += digit num //= 10 # remove last digit print(f"Sum of digits of {original} = {sum_digits}")
Output (for 1234):
pseudoEnter a number: 1234 Sum of digits of 1234 = 10
Tracing (n=1234):
| Iteration | digit (num%10) | num (num//10) | sum_digits |
|---|---|---|---|
| Start | - | 1234 | 0 |
| 1 | 4 | 123 | 4 |
| 2 | 3 | 12 | 7 |
| 3 | 2 | 1 | 9 |
| 4 | 1 | 0 | 10 |
| Exit | - | 0 (loop ends) | 10 |
9.7 Worked Example 3: Reverse a Number
python# runnable num = int(input("Enter a number: ")) original = num reversed_num = 0 while num > 0: digit = num % 10 reversed_num = reversed_num * 10 + digit num //= 10 print(f"Reverse of {original} is {reversed_num}")
Output (for 1234):
pseudoEnter a number: 1234 Reverse of 1234 is 4321
9.8 Worked Example 4: Fibonacci Sequence
Fn=Fn−1+Fn−2where F0=0,F1=1python# runnable n = int(input("How many Fibonacci terms? ")) a, b = 0, 1 count = 0 while count < n: print(a, end=" ") a, b = b, a + b count += 1 print()
Output (for n=10):
pseudoEnter how many Fibonacci terms? 10 0 1 1 2 3 5 8 13 21 34
9.9 Worked Example 5: Collatz Conjecture
Start with any positive n. If even, divide by 2. If odd, multiply by 3 and add 1. Eventually, you reach 1.
python# runnable n = int(input("Enter a positive integer: ")) steps = 0 while n != 1: print(n, end=" → ") if n % 2 == 0: n //= 2 else: n = n * 3 + 1 steps += 1 print("1") print(f"Reached 1 in {steps} steps.")
Output (for n=6):
pseudoEnter a positive integer: 6 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 Reached 1 in 8 steps.
📐 Key Concepts Reference
| Concept | Description | Example |
|---|---|---|
while loop | Repeats while condition is True | while x > 0: |
| Infinite loop | Condition never becomes False | while True: (intentional) or forgetting update |
| Sentinel | Signal value to stop loop | while num != -1: |
| Accumulator | Variable that builds up a result | total += num |
| Loop variable | Variable that controls the loop | i = 1; while i <= 10: i += 1 |
n % 10 | Get last digit of a number | 1234 % 10 → 4 |
n // 10 | Remove last digit | 1234 // 10 → 123 |
While vs For:
| While | For |
|---|---|
| Use when iterations are unknown | Use when iterating over a sequence |
| More flexible (any condition) | More structured |
| Risk of infinite loops | Safer (finite by design) |
| Manual variable update | Automatic iteration |
⚠️ Common Pitfalls
Pitfall 1: Infinite Loop (Forgot to Update)
The mistake:
pythoni = 1 while i <= 10: print(i) # forgot: i += 1
Result: Loop runs forever, printing "1" repeatedly. Fix: Always ensure the loop variable changes toward the exit condition. Detect: If your program doesn't stop, suspect an infinite loop. Add print statements to trace variable values.
Pitfall 2: Off-by-One Errors
The mistake:
while i < 5: when you want 5 iterations. Fix: Trace with small values. while i <= 5: gives 5 iterations (1,2,3,4,5). while i < 5: gives 4 (1,2,3,4).Pitfall 3: Sentinel Loop — Forgetting to Re-Read
The mistake:
pythonnum = float(input("Enter number: ")) while num != -1: total += num # forgot to read next num — infinite loop!
Fix: Always read the next value at the end of the loop body (or use
while True with break).Pitfall 4: Using = Instead of == in Condition
The mistake:
while x = 5: (assignment instead of comparison) The error: SyntaxError: invalid syntax Fix: Use ==: while x == 5:📝 Practice Questions
Q1: How many times does this loop print?pythoni = 0 while i < 5: print(i) i += 1Answer: 5 times (i = 0, 1, 2, 3, 4). When i becomes 5,5 < 5is False, so loop exits. Q2: What's the output?pythonx = 10 while x > 0: x -= 3 print(x)Answer:pseudo-2Trace: x=10 → 7 → 4 → 1 → -2. When x = -2,-2 > 0is False, exit. Print -2. Q3: Write a loop that prints all even numbers from 2 to 20.Answer:python# runnable i = 2 while i <= 20: print(i, end=" ") i += 2Output:2 4 6 8 10 12 14 16 18 20Q4: What does this program do?pythonn = 12345 count = 0 while n > 0: n //= 10 count += 1 print(count)Answer: It counts the number of digits. Output:5Q5: Write a loop that computes the sum: 1² + 2² + 3² + ... + n².Answer:python# runnable n = int(input("Enter n: ")) i = 1 total = 0 while i <= n: total += i ** 2 i += 1 print(f"Sum of squares: {total}")Q6: What's wrong with this code?pythonx = 5 while x > 0: print(x)Answer: Infinite loop!xnever changes. It will print5forever. Fix: addx -= 1inside the loop. Q7: Write a program that keeps asking for a password until the user enters "secret".Answer:python# runnable password = input("Enter password: ") while password != "secret": print("Wrong! Try again.") password = input("Enter password: ") print("Access granted!")Q8: What's the output of this trace?pythona, b = 0, 1 count = 0 while count < 5: print(a, end=" ") a, b = b, a + b count += 1Answer:pseudo0 1 1 2 3Fibonacci sequence: F₀=0, F₁=1, F₂=1, F₃=2, F₄=3 Q9: Write code to find the GCD of two numbers using Euclid's algorithm.Answer:python# runnable a = int(input("Enter a: ")) b = int(input("Enter b: ")) x, y = a, b while y != 0: x, y = y, x % y print(f"GCD({a}, {b}) = {x}")Q10: Write a loop that prints the multiplication table for a given number.Answer:python# runnable n = int(input("Enter number: ")) i = 1 while i <= 10: print(f"{n} × {i} = {n * i}") i += 1
🔗 Cross-References
- Next Topic: For Loops & range()
- Previous Topic: Modules & Import
- BSCS1001 Computational Thinking: Loops are the "iteration" construct in algorithmic thinking.
- Reference: Python for Everybody, Chapter 5 — "Iteration"
- Video: L26: Introduction to while loop, L31: Tutorial on while loop Join Discord Previous8. Modules & ImportNext10. For Loops & range()