Previous | Tutorial index | Next

Tutorial 2: The while Loop – Repeating Based on Conditions

Learning Objective

Understand the syntax of the while loop, grasp the relationship between the loop condition and the body, and learn exactly when to use a while loop instead of a for loop.

1. The Philosophy of the while Loop

Think about a refrigerator light. It stays on while the door is open. Once the door closes (the condition becomes false), the light turns off. You don't know how many times the door will be opened; you just keep the light on as long as the condition is true.

A while loop is the ultimate "keep doing this until something changes" tool in programming. It doesn't count items; it checks a condition before every single repetition. If the condition is True, it runs the code block. If it's False, it skips the block and moves on.

2. The while Loop Syntax

Here is the anatomy of a while loop:

while condition: # Indented code block (the "loop body") # This runs repeatedly AS LONG AS the condition is True.

Breaking it down:

The golden rule of while: Python checks the condition. If it is True, it executes the ENTIRE body. After the body finishes, Python jumps back to the top and checks the condition AGAIN. It repeats this until the condition becomes False.

3. The Countdown Example (Step-by-Step)

Let's trace the classic countdown example to see this in action.

count = 5 while count > 0: print(count) count = count - 1 print("Blast off!")

Mental Trace:

  1. Check 1: count is 5. Is 5 > 0? True. → Print 5. → count becomes 4.
  2. Check 2: count is 4. Is 4 > 0? True. → Print 4. → count becomes 3.
  3. Check 3: count is 3. Is 3 > 0? True. → Print 3. → count becomes 2.
  4. Check 4: count is 2. Is 2 > 0? True. → Print 2. → count becomes 1.
  5. Check 5: count is 1. Is 1 > 0? True. → Print 1. → count becomes 0.
  6. Check 6: count is 0. Is 0 > 0? False. → Python exits the loop and jumps to the line after the indented block (print("Blast off!")).

4. The Menace of Infinite Loops (And How to Slay It)

The most dangerous bug in a while loop is the infinite loop—a loop that never stops because the condition never becomes False. This will freeze your program and crash your IDE or browser.

The Infinite Loop Example:

x = 10 while x > 5: print("Hello") # x never changes! 10 > 5 is ALWAYS True.

How to fix it: You must change something inside the loop that affects the condition.

Safety Nets:

  1. Keyboard Interrupt: If you accidentally run an infinite loop, press Ctrl + C on your keyboard to force-stop the program.
  2. The break Statement: We will cover this in Tutorial 3, but it is an emergency eject button.

💡 Pro-Tip: The "Infinite" Loop Pattern

Sometimes, we intentionally write while True: (which is infinite) and rely on a break statement inside the body to exit. This is extremely common for menu systems:

while True: command = input("Enter a command (or 'quit' to exit): ") if command == "quit": break print(f"You entered: {command}")

5. Counters and Accumulators in while Loops

Because while loops don't automatically give you an index (like range() in a for loop), you have to manage your counters manually.

Counter Example (Print 0 to 4):

i = 0 # Initialize the counter while i < 5: print(i) i += 1 # Increment (Equivalent to i = i + 1)

Accumulator Example (Summing 1 to 10):

total = 0 # Initialize the accumulator num = 1 while num <= 10: total += num # Add num to total num += 1 # Move to the next number print(f"Sum is: {total}") # Output: 55

6. while vs for – The Decision Matrix

How do you decide which loop to use? Many beginners overuse while. Here is a definitive guide:

Feature for Loop while Loop
When to use When you know exactly how many times to iterate. When you don't know how many times it will run, or it depends on a dynamic condition.
Iteration focus Iterates over a sequence (list, string, range). Iterates based on a boolean condition.
Common use cases Processing files, iterating through datasets, math calculations with range(). User input validation, game loops, reading data until EOF, waiting for a sensor to trigger.
Risk of infinite loop Low (Range has a fixed length). High (You must manually update the condition).
Performance Slightly faster in Python due to optimized internal iteration. Slightly slower, but rarely noticeable in beginner tasks.

Rule of Thumb: If you are counting through a range() or a list, use for. If you are saying "keep doing X until Y happens", use while.

7. Common Pitfalls (Watch Out!)

  1. The Forgotten Update (Infinite Loop):

    x = 1 while x < 10: print(x) # Missing: x += 1 # This will print '1' forever.
  2. The continue Disaster: If you use continue in a while loop, ensure the counter updates before the continue statement. Otherwise, you skip the update and cause an infinite loop.

    x = 0 while x < 10: if x % 2 == 0: x += 1 # <-- MUST increment BEFORE continue! continue print(x) x += 1
  3. False Assumptions About Input: If you ask for a number, the user might type a string. Using while with input() requires handling edge cases carefully (which we'll solve in later units with try/except).

  4. Condition Never Becomes False due to Logic Error:

    total = 10 while total > 0: total = total - 0.5 # Works (eventually hits 0) while total != 0: # If total skips over 0, this is infinite! total = total - 0.1 # Might become -0.1 and never hit 0 exactly.

    Fix: Use > or < rather than exact equality (!=) when dealing with floats.

8. Expanded Code Examples

Example 1: Sum of User Inputs (Sentinel Value) This asks the user for numbers and adds them up. Entering 0 stops the loop.

total = 0 number = int(input("Enter a number (0 to stop): ")) while number != 0: total += number number = int(input("Enter a number (0 to stop): ")) print(f"Total sum is: {total}")

Example 2: Password Checker with Max Attempts This combines a counter with a condition to limit tries.

password = "python123" attempts = 3 while attempts > 0: guess = input("Enter password: ") if guess == password: print("Access Granted!") break # Exit the loop immediately else: attempts -= 1 print(f"Wrong! {attempts} attempts left.") if attempts == 0: print("Account Locked.")

Example 3: Simulating a Menu A classic example where while shines.

choice = 0 while choice != 3: print("\n1. Say Hello") print("2. Say Goodbye") print("3. Quit") choice = int(input("Choose an option: ")) if choice == 1: print("Hello there!") elif choice == 2: print("Goodbye for now!") elif choice == 3: print("Exiting...") else: print("Invalid choice, try again.")

📝 Quiz: Check Your Understanding (Part 1)

Take a moment to answer these without running the code!

Q1: How many times does this loop run?

i = 2 while i < 6: print(i) i += 2
Answer(B) 2 times (prints 2,4)

Q2: What is the output of x = 5; while x > 0: print(x, end=" "); x -= 1?

Answer(A) `5 4 3 2 1`

Q3: (True/False) A while loop is the best choice for iterating over every character in a string.

AnswerFalse – a `for` loop is more natural.

Q4: What is wrong with this code?

num = 10 while num >= 0: print(num)
Answer(B) – `num` never changes.

💻 In-Tutorial Coding Exercises

Open your Python IDE or notebook. Write the code for the following challenges. Run them to see if they work!

Exercise 1: Print all even numbers from 20 down to 2 (inclusive).

Solution
num = 20 while num >= 2: print(num) num -= 2

Exercise 2: Calculate the product of numbers from 1 to n (factorial) using while.

Solution
n = 5 product = 1 i = 1 while i <= n: product *= i i += 1 print(product)

Exercise 3: Keep asking for "secret" until correct.

Solution
guess = "" while guess != "secret": guess = input("Enter the secret word: ") print("Access granted!")

Exercise 4: Sum the digits of a positive integer (e.g., 1234 → 10).

Solution
num = 1234 total = 0 while num > 0: total += num % 10 num //= 10 print(total)

Exercise 5: Average of numbers entered until -1 is given.

Solution
count = 0 sum_vals = 0 while True: val = float(input("Enter a number (-1 to stop): ")) if val == -1: break sum_vals += val count += 1 if count > 0: print(f"Average: {sum_vals/count}")

📚 Homework Questions

These problems require deeper logic. Write complete, well-commented Python scripts for each.

Question 1: The Guessing Game (Finite Attempts) Write a program that stores a secret number (e.g., secret = 42). Give the user exactly 5 attempts to guess the number. After each guess, tell them "Too high" or "Too low". If they guess correctly, print "You win!" and exit early. If they run out of attempts, print "You lose! The number was X."

Sample Answer
secret = 42 attempts = 5 while attempts > 0: guess = int(input("Guess: ")) if guess == secret: print("You win!") break elif guess < secret: print("Too low") else: print("Too high") attempts -= 1 if attempts == 0: print(f"Lost. Number was {secret}")

Question 2: Fibonacci Sequence Generator The Fibonacci sequence starts: 1, 1, 2, 3, 5, 8, 13... where each number is the sum of the two preceding ones. Write a program that asks the user for a maximum number limit. Using a while loop, print the Fibonacci sequence up to (but not exceeding) that limit. Example Input: 30 → Output: 1 1 2 3 5 8 13 21

Sample Answer
limit = int(input("Limit: ")) a, b = 1, 1 while a <= limit: print(a, end=" ") a, b = b, a+b

Question 3: Palindrome Number Checker A palindrome reads the same forward and backward (e.g., 121, 1331, 4). Write a program that uses a while loop to reverse a given number (without converting it to a string) and checks if it is a palindrome. Print True or False. (Hint: Use the % 10 and // 10 trick to build a reversed number).

Sample Answer
n = int(input("Number: ")) original = n rev = 0 while n > 0: rev = rev * 10 + n % 10 n //= 10 print(original == rev)

Question 4: The Collatz Conjecture (Advanced Challenge) The Collatz sequence:

Write a program that asks the user for a starting number. Using a while loop, print the entire sequence until it reaches 1, and also count how many steps it took. Example Input: 6 → Output: 6, 3, 10, 5, 16, 8, 4, 2, 1 (Steps: 8)

Sample Answer
n = int(input("Start: ")) steps = 0 while n != 1: print(n, end=" ") if n % 2 == 0: n //= 2 else: n = 3*n + 1 steps += 1 print(n) print(f"Steps: {steps}")

Question 5: Prime Number Validator Write a program that asks the user for a number n. Using a while loop, check if n is a prime number (only divisible by 1 and itself). You only need to check divisors up to n/2 or sqrt(n). Print "Prime" or "Not Prime". (Hint: Use a counter divisor = 2 and a boolean flag is_prime = True).

Sample Answer
n = int(input("Number: ")) is_prime = True if n < 2: is_prime = False else: d = 2 while d * d <= n: if n % d == 0: is_prime = False break d += 1 print("Prime" if is_prime else "Not prime")

Congratulations! You have successfully conquered the while loop. Remember: The for loop is for collections, and the while loop is for conditions. Knowing the difference is the hallmark of a good programmer. Next, we will learn how to manipulate these loops with break and continue!

Previous | Tutorial index | Next