🔁 While Loops

Repeat code while a condition is true - perfect for when you don't know how many times to repeat!

What you'll learn:

  • What while loops are and when to use them
  • The difference between while loops and for loops
  • How to avoid infinite loops
  • Using while loops for input validation

For Loops vs While Loops

🔄 For Loop

Use when: You know how many times to repeat

# Print "Hello" 5 times
for i in range(5):
    print("Hello")

We know exactly: 5 times

🔁 While Loop

Use when: You don't know how many times - repeat until something happens

# Keep asking until correct
answer = ""
while answer != "yes":
    answer = input("Ready? ")

Could be 1 time, could be 100!

While Loop Syntax

A while loop keeps running as long as its condition is True.

while_loop_structure.py
while condition:
    # Code to repeat
    # This runs while condition is True
    # Must change something to eventually make condition False!
while Keyword that starts the loop
condition Checked before each iteration - loop continues while True
: Colon marks the start of the loop body
indented code Code inside the loop - must be indented

Common While Loop Patterns

1. Counting with While

Count up or down until reaching a target.

# Count from 1 to 5
count = 1
while count <= 5:
    print(count)
    count = count + 1  # Important!

# Output: 1, 2, 3, 4, 5
Key: Always update the variable used in the condition!

2. Input Validation

Keep asking until the user enters valid input.

# Keep asking until valid age entered
age = -1
while age < 0 or age > 120:
    age = int(input("Enter age (0-120): "))

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

3. Password/Menu Loop

Repeat until a specific value is entered.

# Simple password check
password = ""
while password != "secret123":
    password = input("Enter password: ")

print("Access granted!")

4. While True with Break

Loop forever until break is called - useful for menus.

while True:
    choice = input("Enter Q to quit: ")
    if choice == "Q":
        break  # Exit the loop
    print("You entered:", choice)

print("Goodbye!")

Avoiding Infinite Loops

What is an Infinite Loop?

An infinite loop is a loop that never stops because its condition never becomes False. This will freeze your program!

Bad - Infinite Loop!

# This will run FOREVER!
count = 1
while count <= 5:
    print(count)
    # Forgot to increase count!
    # count is always 1, always <= 5

Good - Loop Terminates

# This stops after 5 iterations
count = 1
while count <= 5:
    print(count)
    count = count + 1  # count changes!
    # Eventually count > 5
Tip: If your program freezes, press Ctrl + C to stop it!

Break and Continue

Two special keywords that control loop flow:

break

Immediately exits the loop completely.

count = 0
while True:
    count = count + 1
    if count == 3:
        break  # Exit loop
    print(count)

# Output: 1, 2
# (3 is never printed - loop exits)

continue

Skips to the next iteration of the loop.

count = 0
while count < 5:
    count = count + 1
    if count == 3:
        continue  # Skip to next
    print(count)

# Output: 1, 2, 4, 5
# (3 is skipped)

Learning Path

Follow these activities in order to master while loops.

Key Vocabulary

while loop

A loop that repeats while a condition is True.

condition

A Boolean expression checked before each iteration.

iteration

One execution of the loop body.

infinite loop

A loop that never stops because the condition never becomes False.

break

A keyword that immediately exits the loop.

continue

A keyword that skips to the next iteration.

Quick Reference

while_loop_reference.py
# Basic while loop
while condition:
    # code to repeat

# Counting pattern
count = 1
while count <= 10:
    print(count)
    count = count + 1

# Input validation pattern
while True:
    user_input = input("Enter value: ")
    if is_valid(user_input):
        break
    print("Invalid, try again")

# Menu pattern
choice = ""
while choice != "quit":
    choice = input("Enter choice: ")
    # process choice