Basic while Loops

While Loops

Basic while Loops

In this tutorial, we'll repeat code using a condition.

A while loop repeats code while a condition is true.

count = 1

while count <= 3:
    print(count)
    count = count + 1

Output:

1
2
3

How It Works

Python checks the condition before each loop run:

1. Is count <= 3 true? 2. If yes, run the indented code 3. Update count 4. Check the condition again

When the condition becomes false, the loop stops.

while vs for

Use a while loop when you do not know exactly how many times the loop will run.

For example, keep asking until a password is correct:

password = ""

while password != "python":
    password = input("Password: ")

The condition is checked after every attempt. As soon as the password equals "python", the loop stops.

A Simple Countdown

countdown = 3

while countdown > 0:
    print(countdown)
    countdown = countdown - 1

print("Start")

This kind of example is useful because you can clearly see the value moving toward the stopping point.

Common Mistake

Forgetting to update the condition can create an infinite loop:

count = 1

while count <= 3:
    print(count)

count never changes, so the loop never ends.

Practice

Use a while loop to print the numbers from 1 to 5.