While Loops

Week 1 — Python Basics Revision

Introduction

A for loop runs a set number of times. But what if you do not know when to stop? A while loop keeps running as long as a condition remains True — perfect for situations like "keep asking until the user enters a valid password."

The While Loop

A while loop checks its condition before each iteration. If the condition is True, it runs the body. Then it checks again. When the condition becomes False, the loop stops.

count = 1

while count <= 5:
    print(f"Count: {count}")
    count += 1

print("Done!")
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done!

The flow is: check condition, run body, repeat. Each time through the loop, count increases by 1. When count reaches 6, the condition count <= 5 is False, and the loop stops.

User Input Validation

A very common use case for while loops is validating user input. The loop keeps asking until the user gives a valid answer.

age = -1

while age < 0 or age > 120:
    age = int(input("Enter a valid age (0-120): "))

print(f"Your age: {age}")

We set age = -1 so the condition is True on the first check. The loop keeps prompting until the user enters a number between 0 and 120.

The break Statement

The break statement exits the loop immediately, no matter what the condition says.

while True:
    command = input("Type 'quit' to exit: ")
    if command == "quit":
        print("Goodbye!")
        break
    print(f"You typed: {command}")

The while True creates a loop that would run forever on its own. The break inside gives us a clean way to exit when the right condition is met.

The continue Statement

The continue statement skips the rest of the current iteration and jumps back to the top of the loop.

for i in range(1, 11):
    if i % 3 == 0:
        continue
    print(i, end=" ")
# Output: 1 2 4 5 7 8 10
Output
1 2 4 5 7 8 10

Numbers divisible by 3 (3, 6, 9) are skipped. The continue causes the loop to go straight to the next iteration without running the print.

Avoiding Infinite Loops

Warning: A while loop with a condition that never becomes False runs forever. Always make sure something inside the loop changes the condition.

# BAD - infinite loop!
# x = 1
# while x > 0:
#     print(x)    # x never changes!

# GOOD - x eventually reaches 0
x = 5
while x > 0:
    print(x)
    x -= 1
Output
5
4
3
2
1

Real-World Example

A simple menu system that lets the user deposit, withdraw, or exit. This is the kind of loop you will see in many real programs.

balance = 1000

while True:
    print(f"\nBalance: ${balance:.2f}")
    print("1. Deposit")
    print("2. Withdraw")
    print("3. Exit")

    choice = input("Choose: ")

    if choice == "1":
        amount = float(input("Amount: $"))
        balance += amount
    elif choice == "2":
        amount = float(input("Amount: $"))
        if amount <= balance:
            balance -= amount
        else:
            print("Insufficient funds.")
    elif choice == "3":
        print("Goodbye!")
        break

This uses the while True + break pattern. The loop runs until the user picks option 3, which triggers the break.

How This Connects to OOP

While loops power many interactive systems. In OOP, a method might use a while loop to retry an operation or wait for valid input. Game loops, server listeners, and menu systems all use while True with break.

Best Practices

  • Use for when you know the count, while when you do not
  • Always ensure the condition can become False
  • while True + break is a clean pattern for menus
  • Keep loop bodies short and focused

Common Mistakes

  • Forgetting to update the loop variable — causes an infinite loop
  • Using while when for would be simpler
  • Not testing the exit condition before deploying your code

Practice Exercises

  1. Write a countdown from 10 to 1 using a while loop, then print "Liftoff!"
  2. Keep asking the user for a password until they enter "secret123".
  3. Create a simple number guessing game: pick a number, let the user guess until correct.

Summary

You now know both for and while loops. The final building block before OOP is functions — reusable blocks of code. That is next.