0%

21- The while Loop

Loop until a condition becomes False. Perfect when you don’t know how many iterations you need. Repeat while something is true.

The for loop is for when you know what you are looping over. A list. A string. A range. The number of iterations is known (or at least bounded). But sometimes you do not know. You want to keep asking the user for input until they give a valid answer. You want to keep processing data while there is more to read. You want to count down from 10 to 1. The number of iterations depends on something that happens during the loop. This is where the while loop shines. It repeats as long as a condition remains True. When the condition becomes False, the loop stops. It is the most flexible loop structure in Python.

🕯️ Magic Note

The while loop is the original loop in programming. Early languages had only while and goto. for loops are actually a convenient abstraction built on top of while. Understanding while means understanding the foundation of all iteration.

Basic while Loop Syntax
The syntax is simple. The word while, followed by a condition, then a colon. The indented block runs repeatedly as long as the condition is True.

Python

# Simple counter

count = 1

while count <= 5:

print(count)

count += 1

# Output:

# 1

# 2

# 3

# 4

# 5

⚠️ If the condition never becomes False, the loop runs forever. This is called an infinite loop. Always ensure something inside the loop changes the condition.
The Infinite Loop (and How to Avoid It)
An infinite loop never stops. Sometimes you want this (like a game loop or a server). Most times, it is a bug. Press Ctrl+C to stop a running infinite loop.

Python

# INFINITE LOOP (dangerous!)

# while True:

# print(“This never stops”)

# Common mistake: forgetting to update the variable

x = 0

# while x < 10:

# print(x)

# # x never changes! Infinite loop!

# Correct way

x = 0

while x < 10:

print(x)

x += 1 # Update condition variable

💡 When debugging, add a safety counter to suspicious loops: if safety > 1000: break. This prevents accidental infinite loops.
while vs for: When to Use Which
Choose for when you know the sequence. Choose while when you know the condition.
Use for When...Use while When...
Iterating over a list, tuple, string, or rangeCondition depends on runtime values
Number of iterations is known (or bounded)Number of iterations is unknown in advance
You need to transform each element of a sequenceReading from a file until EOF
You want to loop a fixed number of timesUser input validation (keep asking until valid)
You want the most readable, Pythonic optionYou need infinite loops (game loops, servers)

Python

# For loop: known sequence

for fruit in [“apple”, “banana”, “cherry”]:

print(fruit)

# While loop: unknown number of iterations

user_input = “”

while user_input != “quit”:

user_input = input(“Enter ‘quit’ to exit: “)

print(f”You entered: {user_input}”)

User Input Validation (Classic Use Case)
Keep asking the user until they provide valid input. You cannot know how many attempts they will need.

Python

# Keep asking until user enters a positive number

num = -1

while num < 0:

num = int(input(“Enter a positive number: “))

if num < 0:

print(“That is not positive. Try again.”)

print(f”Thanks! You entered {num}”)

# With error handling

while True:

try:

age = int(input(“Enter your age: “))

if 0 <= age <= 120:

break

print(“Please enter a valid age (0-120)”)

except ValueError:

print(“That is not a number. Try again.”)

print(f”Age: {age}”)

🕯️ Magic Note

The pattern while True with a break inside is very common. It means “loop forever, but break when a condition is met”. This is often cleaner than checking a condition at the top, especially when the exit condition is in the middle of the loop.

Counting Down with while
A natural fit for while is counting down from a number to something.

Python

# Countdown

count = 10

while count > 0:

print(count)

count -= 1

print(“Blast off!”)

# Output:

# 10

# 9

# …

# 1

# Blast off!

Reading Files Until EOF
Reading a file line by line until the end is a classic while pattern. But Python’s for loop is actually better for this.

Python

# While loop style (old school)

with open(“data.txt”, “r”) as f:

line = f.readline()

while line:

print(line.strip())

line = f.readline()

# Better: for loop (Pythonic)

with open(“data.txt”, “r”) as f:

for line in f:

print(line.strip())

break and continue in while Loops
Just like in for loops, break exits immediately, and continue skips to the next iteration.

Python

# break: exit the loop

num = 1

while num <= 100:

if num * num > 50:

break

print(f”{num}^2 = {num**2}”)

num += 1

# continue: skip to next iteration

num = 0

while num < 10:

num += 1

if num % 2 == 0:

continue

print(num, end=” “)

# 1 3 5 7 9

The else Clause in while (Rare but Useful)
Like for, while can have an else clause. The else block runs if the loop ends normally (without a break).

Python

# Search a list until found

items = [1, 3, 5, 7, 9]

target = 4

i = 0

while i < len(items):

if items[i] == target:

print(f”Found {target} at index {i}”)

break

i += 1

else:

print(f”{target} not found”)

# Output: 4 not found

⚠️ The else in loops is often confusing. Remember: it runs when no break occurred. If you are confused, simply use a flag variable instead.
while with a Flag Variable
Sometimes using a boolean flag makes the loop logic clearer, especially with complex conditions.

Python

# Using a flag variable

is_running = True

attempts = 0

while is_running and attempts < 3:

password = input(“Enter password: “)

if password == “magic”:

print(“Access granted”)

is_running = False

else:

attempts += 1

print(f”Wrong. {3 – attempts} attempts left”)

if attempts == 3:

print(“Access denied”)

Nested while Loops
You can put a while loop inside another while loop. This is useful for tables, grids, or repeated validation.

Python

# Multiplication table (1 to 5)

i = 1

while i <= 5:

j = 1

while j <= 5:

print(f”{i} x {j} = {i * j}”, end=” “)

j += 1

print()

i += 1

Simulating a for Loop with while
Any for loop can be rewritten as a while loop. Understanding this helps you see how iteration works under the hood.

Python

# For loop

for i in range(5):

print(i)

# Equivalent while loop

i = 0

while i < 5:

print(i)

i += 1

🕯️ Magic Note

A for loop is essentially a while loop with a built-in iterator. The for loop automatically fetches the next item and handles the StopIteration exception. This is why for is preferred: it is safer and less error-prone.

Practical Example: Menu System
A classic use of while is a menu that keeps showing options until the user chooses to exit.

Python

# Simple menu system

choice = 0

while choice != 3:

print(“\n=== Main Menu ===”)

print(“1. Say Hello”)

print(“2. Show Date”)

print(“3. Exit”)

choice = int(input(“Select option: “))

if choice == 1:

print(“Hello, dear user!”)

elif choice == 2:

from datetime import date

print(f”Today is {date.today()}”)

elif choice == 3:

print(“Goodbye!”)

else:

print(“Invalid option. Try again.”)

Common Mistakes with while Loops
  • Forgetting to update the condition variable (infinite loop)
  • Using == instead of = when updating variables
  • Off-by-one errors (check your comparison operators: < vs <=)
  • Using while for simple iteration when for would be cleaner
  • Confusing break (exits loop) with continue (skips iteration)
  • Putting a semicolon after the condition (like C/C++): while x < 10;
  • Not handling the case where the loop should run zero times
Check Your Understanding
  • Write a while loop that prints numbers from 1 to 10.
  • What is an infinite loop and how do you avoid it?
  • Write a input validation loop that keeps asking until the user enters “yes” or “no”.
  • What is the difference between break and continue?
  • When should you use while instead of for?
  • What does the else clause do in a while loop?

⚡ Whisper

The while loop is patient. It asks a question, then waits. If the answer is Yes, it takes one step. Then it asks again. And again. It does not know how many steps it will take. It only knows the question. Is the user done? Is the file empty? Is the number still small? These are the questions that guide the while loop. It is the loop of uncertainty. The loop of waiting. The loop of “I will continue until something changes.” Master the while loop, and you master situations where the end is not known in advance. You learn to trust the condition, not a fixed count. You learn to be patient. You learn to ask. Again. And again. Until the answer changes.

Related posts