Quiz 2
Registry Synced

While Loops

1786 words
9 min read

Reading compass

Now · 🎯 Learning Objectives

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:
  1. Write while loops that repeat code based on a condition
  2. Avoid and fix infinite loops
  3. Use accumulator patterns (sum, product, count)
  4. Implement sentinel-controlled loops (repeat until a signal value)
  5. Choose between while and for loops

📋 Prerequisites


📖 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:
pseudo
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop ended!
How it works:
  1. Check count <= 5 → True, enter loop
  2. Print count (1), then count += 1 (count becomes 2)
  3. Back to top, check again: 2 <= 5 → True
  4. ... repeat until count becomes 6
  5. 6 <= 5 → False, exit loop Diagram Rendering 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×(n1)×(n2)×...×1n! = n \times (n-1) \times (n-2) \times ... \times 1
python
# 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):
pseudo
Enter n: 5
5! = 120
Tracing the loop (n=5):
Iterationifactorial
Start11
11→21*1 = 1
22→31*2 = 2
33→42*3 = 6
44→56*4 = 24
55→624*5 = 120
Exit6 (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):
pseudo
Enter a number: 1234
Sum of digits of 1234 = 10
Tracing (n=1234):
Iterationdigit (num%10)num (num//10)sum_digits
Start-12340
141234
23127
3219
41010
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):
pseudo
Enter a number: 1234
Reverse of 1234 is 4321

9.8 Worked Example 4: Fibonacci Sequence

Fn=Fn1+Fn2where F0=0,F1=1F_n = F_{n-1} + F_{n-2} \quad \text{where } F_0 = 0, F_1 = 1
python
# 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):
pseudo
Enter 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):
pseudo
Enter a positive integer: 6
6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1
Reached 1 in 8 steps.

📐 Key Concepts Reference

ConceptDescriptionExample
while loopRepeats while condition is Truewhile x > 0:
Infinite loopCondition never becomes Falsewhile True: (intentional) or forgetting update
SentinelSignal value to stop loopwhile num != -1:
AccumulatorVariable that builds up a resulttotal += num
Loop variableVariable that controls the loopi = 1; while i <= 10: i += 1
n % 10Get last digit of a number1234 % 104
n // 10Remove last digit1234 // 10123
While vs For:
WhileFor
Use when iterations are unknownUse when iterating over a sequence
More flexible (any condition)More structured
Risk of infinite loopsSafer (finite by design)
Manual variable updateAutomatic iteration

⚠️ Common Pitfalls

Pitfall 1: Infinite Loop (Forgot to Update)

The mistake:
python
i = 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:
python
num = 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?
python
i = 0
while i < 5:
    print(i)
    i += 1
Answer: 5 times (i = 0, 1, 2, 3, 4). When i becomes 5, 5 < 5 is False, so loop exits. Q2: What's the output?
python
x = 10
while x > 0:
    x -= 3
print(x)
Answer:
pseudo
-2
Trace: x=10 → 7 → 4 → 1 → -2. When x = -2, -2 > 0 is 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 += 2
Output: 2 4 6 8 10 12 14 16 18 20 Q4: What does this program do?
python
n = 12345
count = 0
while n > 0:
    n //= 10
    count += 1
print(count)
Answer: It counts the number of digits. Output: 5 Q5: 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?
python
x = 5
while x > 0:
    print(x)
Answer: Infinite loop! x never changes. It will print 5 forever. Fix: add x -= 1 inside 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?
python
a, b = 0, 1
count = 0
while count < 5:
    print(a, end=" ")
    a, b = b, a + b
    count += 1
Answer:
pseudo
0 1 1 2 3
Fibonacci 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

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.