Python while Loop

In the last lesson, we learned about the Python for Loop. Now let’s repeat code when we do not know in advance how many rounds we will need.

Let’s Talk About a Different Kind of Loop

In the last article, we learned about the for loop. It is great when we know how many times we want to repeat something.

But what if we do not know?

What if we want to keep doing something until a certain condition is met?

That is where the while loop comes in.

What Is a Python while Loop?

A while loop repeats code as long as a condition is true.

It is like a for loop, but instead of going through a sequence, it keeps going until the condition becomes false.

Think of it like this. We are filling a bucket with water. We keep pouring until the bucket is full. We do not know exactly how many pours it will take. We just keep going while the bucket is not full.

That is a while loop.

The Structure of a Python while Loop

while condition:
# do something
  • while — the keyword
  • condition — something that gives True or False
  • : — the colon
  • Then indented code — what to do while the condition is true

The code runs again and again as long as the condition is true. The moment it becomes false, the loop stops.

A Simple Python while Loop Example

Let’s count from 1 to 5 using a while loop.

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

Output

1
2
3
4
5

Let me explain what happened.

  • count starts at 1.
  • The condition count <= 5 is checked. Is 1 <= 5? Yes. So the loop runs.
  • It prints count (1). Then increases count by 1. Now count is 2.
  • Check again. Is 2 <= 5? Yes. Run again.
  • This continues until count becomes 6.
  • When count is 6, the condition 6 <= 5 is False. So the loop stops.

That is how a while loop works. It keeps going until the condition becomes false.

Important — Do Not Forget to Update

Here is a mistake that every beginner makes.

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

What happens here? Nothing updates count. So count stays 1 forever. And the condition 1 <= 5 is always true. So the loop runs forever.

This is called an infinite loop. It never stops. Our program will freeze. We will have to force-close it.

Let’s always make sure something inside the loop changes the condition. Usually, we update the variable that the condition depends on.

count = 1
while count <= 5:
print(count)
count += 1 # This is important!

Without that count += 1, the loop would never end.

Python while Loop: A Real-Life Example

Let’s ask the user for a password. Keep asking until they get it right.

password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted")

If the user enters “secret” the first time, the loop runs once and stops.

If they enter something else, it keeps asking.

That is a while loop. It keeps going until the condition is false.

Another Example — Sum Until Zero

Let’s ask the user for numbers. Add them up. Stop when they enter 0.

total = 0
number = int(input("Enter a number (0 to stop): "))
while number != 0:
total += number
number = int(input("Enter a number (0 to stop): "))
print(f"Total: {total}")

If the user enters 5, 10, 3, then 0:

  • Start with total = 0.
  • Enter 5. 5 != 0, so total = 5. Ask again.
  • Enter 10. 10 != 0, so total = 15. Ask again.
  • Enter 3. 3 != 0, so total = 18. Ask again.
  • Enter 0. 0 != 0 is False. Loop stops.
  • Print total: 18.

That is a classic while loop pattern. Do something until a special value is entered.

while vs for in Python

When should we use while? When should we use for?

Use for when:

  • We know how many times we want to loop
  • We are going through a list, string, or range

Use while when:

  • We do not know how many times we will loop
  • We are looping until a condition is met
  • We are waiting for something to happen

For example:

  • for loop: “Do this 10 times”
  • while loop: “Keep doing this until the user says stop”

Both are useful. Let’s pick the one that fits.

The else Clause with while in Python

Python allows an else block with a while loop. The else runs when the loop finishes normally. Not when it is stopped by break.

count = 1
while count <= 3:
print(count)
count += 1
else:
print("Loop finished")

Output

1
2
3
Loop finished

The else runs because the loop finished naturally. We will learn more about break later. For now, let’s just know that else is optional and runs after the loop ends.

Most beginners do not use while-else. But it exists.

Common Mistakes with Python while Loop

Mistake 1: Infinite Loop

Here is a mistake that will make our program freeze.

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

This prints 1 forever. Because count never changes.

To stop it, we would have to force-close the program.

So what do we do? We update the variable.

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

Let’s always ask ourselves: “What changes inside this loop?” If nothing changes, it is an infinite loop.

Mistake 2: Condition Never Becomes False

x = 10
while x > 5:
print(x)
x += 1

Here, x keeps increasing. So x > 5 stays true forever. Because x never goes below 5. It just keeps getting bigger.

That is also an infinite loop.

So what do we do? We make sure the condition can eventually become false.

x = 10
while x > 5:
print(x)
x -= 1

Now x decreases. So eventually, x > 5 becomes false. And the loop stops.

A Real-Life Example — Guessing Game

Let’s build a simple guessing game.

secret = 7
guess = 0
while guess != secret:
guess = int(input("Guess the number (1-10): "))
if guess < secret:
print("Too low")
elif guess > secret:
print("Too high")
print("You got it!")

The loop keeps asking until the user guesses the right number.

If the user enters 3, it says “Too low”. Then asks again.

If they enter 9, it says “Too high”. Then asks again.

When they enter 7, the loop stops. And it prints “You got it!”.

That is a great use of a while loop. We do not know how many guesses it will take.

Next, we will learn about the Python break Statement and stop a loop before it finishes normally.