While Loops Basics

What is a While Loop?

A while loop repeats code as long as a condition is True. Unlike for loops that iterate over a sequence, while loops continue until the condition becomes False.

Basic While Loop Syntax

while condition:
    # Code to repeat
    pass

The loop continues as long as condition is True.

Your First While Loop

Here's a simple example:

count = 0
while count < 5:
    print(count)
    count = count + 1

Output:

0
1
2
3
4

The loop runs while count < 5 is True. When count becomes 5, the condition is False and the loop stops.

Understanding the Condition

The condition is checked before each iteration:

number = 1
while number <= 5:
    print(f"Number: {number}")
    number = number + 1

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

While vs For Loops

For loops: Use when you know how many times to repeat or when iterating over a collection.

While loops: Use when you want to repeat until a condition changes.

# For loop - we know we want 5 iterations
for i in range(5):
    print(i)

# While loop - repeat until condition is false
count = 0
while count < 5:
    print(count)
    count = count + 1

Both produce the same output, but for loops are usually clearer when you know the number of iterations.

Practical Examples

Example 1: Counting Up

number = 1
while number <= 10:
    print(number)
    number = number + 1

Example 2: User Input Validation

# Simulating user input
password = ""
while password != "secret":
    password = "secret"  # In real code, this would be input()
    if password != "secret":
        print("Wrong password, try again!")
print("Access granted!")

Example 3: Processing Until Done

tasks = ["task1", "task2", "task3"]
while tasks:
    current_task = tasks.pop(0)
    print(f"Processing: {current_task}")
print("All tasks done!")

Output:

Processing: task1
Processing: task2
Processing: task3
All tasks done!

Common Patterns

Pattern 1: Counter Pattern

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

Pattern 2: Accumulator Pattern

total = 0
number = 1
while number <= 10:
    total = total + number
    number = number + 1
print(f"Sum: {total}")  # Output: Sum: 55

Pattern 3: Flag Pattern

found = False
search_value = 5
numbers = [1, 2, 3, 4, 5, 6]
index = 0

while not found and index < len(numbers):
    if numbers[index] == search_value:
        found = True
        print(f"Found at index {index}")
    index = index + 1

Important: Updating the Condition

Critical: You must update the variable in the condition, or you'll create an infinite loop!

# This is an infinite loop - DON'T RUN THIS!
# count = 0
# while count < 5:
#     print(count)
#     # Forgot to increment count!

# Correct version:
count = 0
while count < 5:
    print(count)
    count = count + 1  # Must update!

Infinite Loops

An infinite loop runs forever because the condition never becomes False:

# This runs forever - DON'T RUN THIS!
# while True:
#     print("This never stops!")

# To stop an infinite loop, press Ctrl+C

Sometimes infinite loops are useful (like game loops), but usually they're bugs!

Breaking Out of Loops

You can use break to exit a loop early (we'll cover this in detail later):

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

Common Mistakes

  1. Forgetting to update the condition variable: This creates an infinite loop python # Wrong - infinite loop! count = 0 while count < 5: print(count) # Missing: count = count + 1

  2. Wrong condition: Make sure the condition can become False python # Wrong - always True! while 1 < 2: # This is always True! print("Looping...")

  3. Using = instead of ==: Assignment vs comparison ```python # Wrong - this assigns, not compares! while count = 5: # Error! print(count)

# Correct while count == 5: # Compares print(count) ```

When to Use While Loops

Use while loops when: - You don't know how many iterations you need - You're waiting for a condition to change - You're processing data until it's empty - You're validating user input - You're implementing game loops or event loops

Try It Yourself!

Create a while loop that prints numbers from 10 down to 1:

number = 10
while number >= 1:
    print(number)
    number = number - 1

Practice Tips

  • Always make sure the condition can become False
  • Always update variables used in the condition
  • Use for loops when you know the number of iterations
  • Use while loops when the number of iterations is unknown
  • Be careful of infinite loops!

What's Next?

Now you understand basic while loops! Next, we'll learn about using while loops with more complex conditions.

While Loops Basics

points

You earned points! 🎉 Keep practicing! 💪

Sign up to save your points and access 10,000+ exercises Sign up to track your progress and access 10,000+ exercises

Daily Limit Reached

🔥 exercises left — Upgrade for more!

This module requires

Try the first module of this course for free, then upgrade to unlock all modules and exercises.

No exercise selected

Click "New Exercise" to begin

Generating exercise...

Syntax Syntax OK Syntax off

Write a short answer to the question above (2-5 sentences).

Score
+ /
Base /10
Bonus
×
Total
+

Feedback

Tip

Your Solution

Correct Solution