DocsHub
Loops

While Loops

Learn how to repeat code as long as a condition is true using while loops in Python.

While Loops

A while loop repeats a block of code as long as a condition is true. Unlike a for loop where you know the sequence upfront, a while loop keeps going until something changes.

count = 0

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

Output:

0
1
2
3
4

Python checks the condition before every iteration. If it is true, run the block. If it is false, stop.


How it works

Yes No Start Is condition true? Run the loop block Update something Loop ends

The key difference from a for loop — you are responsible for changing something inside the loop. If nothing changes, the condition stays true forever.


The structure

while condition:
    code to run
    update something so the condition eventually becomes false

Always ask yourself — what will make this condition false? If the answer is nothing, you have an infinite loop.


A simple counter

number = 1

while number <= 10:
    print(f"{number} x 2 = {number * 2}")
    number += 1

Output:

1 x 2 = 2
2 x 2 = 4
3 x 2 = 6
...
10 x 2 = 20

number += 1 is what makes the loop eventually stop. Every iteration, number gets bigger until it exceeds 10.


Infinite loops

An infinite loop runs forever because the condition never becomes false. This is almost always a bug.

# Danger — this runs forever
count = 0

while count < 5:
    print(count)
    # forgot count += 1 — count stays 0 forever

If you accidentally run an infinite loop, press Ctrl + C in your terminal to stop it.

Always make sure something inside your while loop moves it closer to the exit condition. Forgetting to update the variable is the most common while loop bug.


while True — loop until you decide to stop

Sometimes you genuinely do not know when to stop — you just want to keep going until something specific happens. while True is the pattern for this. It loops forever on purpose, and you use break to exit when you are ready.

while True:
    password = input("Enter your password: ")

    if password == "secret123":
        print("Access granted!")
        break
    else:
        print("Wrong password. Try again.")

Output:

Enter your password: hello
Wrong password. Try again.
Enter your password: secret123
Access granted!

The loop keeps asking until the user gets it right. Once they do, break exits the loop immediately. You will learn more about break in the next file.


Counting down

countdown = 10

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

print("Blast off!")

Output:

10
9
8
...
1
Blast off!

Using while to validate input

A very common real-world pattern — keep asking for input until the user gives you something valid:

while True:
    age = input("Enter your age: ")

    if age.isdigit():
        age = int(age)
        break
    else:
        print("That is not a valid age. Please enter a number.")

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

Output:

Enter your age: hello
That is not a valid age. Please enter a number.
Enter your age: -5
That is not a valid age. Please enter a number.
Enter your age: 22
Your age is 22.

isdigit() checks if every character in the string is a digit. If yes, it is safe to convert to int.


for vs while — when to use which

SituationUse
You know the sequence or count upfrontfor
You are iterating over a list, string, dictfor
You do not know how many times to repeatwhile
You are waiting for a condition to changewhile
You are validating user inputwhile
You want to loop until something specific happenswhile True + break

A good rule — reach for for first. If you cannot express it cleanly with for, use while.


A real example

A simple guessing game:

secret = 42
attempts = 0

while True:
    guess = int(input("Guess the number: "))
    attempts += 1

    if guess < secret:
        print("Too low. Try again.")
    elif guess > secret:
        print("Too high. Try again.")
    else:
        print(f"Correct! You got it in {attempts} attempts.")
        break

Output:

Guess the number: 20
Too low. Try again.
Guess the number: 60
Too high. Try again.
Guess the number: 42
Correct! You got it in 3 attempts.

Summary

ConceptExample
Basic while loopwhile condition:
Loop foreverwhile True:
Exit the loopbreak
Update the variablecount += 1
Validate inputwhile True: + if valid: break

On this page