Loops are everywhere in Python. From printing a list to running a game, almost every real program uses them at some point. And when it comes to loops, the while loop in Python is one of the first things you should actually understand.
Most beginners make one mistake: they learn the syntax and move on. But that is not enough. You need to understand how a while loop thinks. As a result, you will write better code and avoid bugs that are hard to trace later.
Now, what exactly does a while loop do? It runs a block of code again and again, as long as a condition is true. The condition gets checked every time before the loop runs. The second that condition turns false, the loop stops and Python moves forward. That is the core idea. But there is a lot more to explore in the while loop in Python. In this guide, we will walk through the while loop in Python from the ground up. You will see the syntax, step-by-step examples, control statements like break and continue, real-world use cases, common mistakes, and answers to questions people actually search for. By the end, you will know exactly when to use a while loop and how to use it well.
Read Also: Python Program to Check Armstrong Number
A while loop in Python is a control flow statement. It repeats a block of code as long as a given condition evaluates to True.
You can think of it like this: imagine you are filling a glass of water. You keep pouring as long as the glass is not full. The moment it is full, you stop. That is exactly how a while loop works.
Python checks the condition before every iteration. If the condition is True, it runs the code block. If it is False, it exits the loop and moves to the next line of the program.
This makes the while loop different from the for loop. A for loop runs for a fixed number of times. A while loop runs until a condition changes. You use a while loop when you do not know in advance how many times the loop will run.
The syntax of a while loop in Python is clean and easy to read.
|
while condition: statement(s) |
Here is what each part means:
while is the keyword that starts the loop.
condition is a boolean expression. The loop runs as long as it evaluates to True.
statement(s) represent the block of code that runs during each iteration. You must indent this block.
Important: Python uses indentation to define the body of the loop. Always use consistent indentation (4 spaces is the standard).
Let us walk through how Python executes a while loop:
Python evaluates the condition.
If the condition is True, Python runs the code block inside the loop.
After the code block runs, Python goes back to step 1 and checks the condition again.
If the condition is False, Python skips the loop body and moves to the next line after the loop.
This cycle is called an iteration. Each time the loop runs its body, that is one iteration.
Read Also: What is Switch Case in Python?
Let us start with a simple example. We will print numbers from 1 to 5 using a while loop.
|
number = 1 while number <= 5: print(number) number += 1 |
Output:
|
1 2 3 4 5 |
Here's what happens step by step:
number starts at 1.
Python checks if number <= 5. It is True, so it runs the body.
It prints 1 and then adds 1 to the number. Now the number is 2.
Python checks again. 2 <= 5 is True. It prints 2.
This continues until the number becomes 6.
Python checks 6 <= 5. It is False. The loop exits.
A counter variable is the most common way to control a while loop in Python. You set a starting value, check it in the condition, and update it inside the loop.
|
count = 0 while count < 3: print("Learning Python while loop") count += 1 |
Output:
|
Learning Python while loop Learning Python while loop Learning Python while loop |
Always make sure you update the counter inside the loop. If you forget, the loop will run forever.
Related Article: Online Python Compiler
An infinite loop is a while loop where the condition never becomes False. Python keeps running the loop endlessly until you stop the program manually (usually with Ctrl + C).
|
while True: print("This runs forever") |
You will sometimes use infinite loops on purpose. For example, a program that waits for user input or a server that listens for incoming connections.
|
while True: user_input = input("Enter a command (or 'quit' to exit): ") if user_input == "quit": break print(f"You entered: {user_input}") |
In this example, the loop runs until the user types quit. The break statement handles the exit.
Avoid creating accidental infinite loops. Always make sure your condition will eventually become False or that you have a break statement to exit.
Python gives you three control statements to manage how a while loop runs. These are break, continue, and pass.
The break statement exits the loop immediately. It does not matter whether the condition is still True. Python stops the loop and moves to the next line after it.
|
number = 0 while number < 10: if number == 5: break print(number) number += 1 |
Output:
|
0 1 2 3 4 |
The loop would normally run until the number reaches 10. But when number equals 5, the break statement fires and the loop ends.
When should you use break? Use break when you have found what you were looking for and do not need to keep looping.
Read Also: Python vs JavaScript: A Comparison Guide
The continue statement skips the rest of the current iteration. Python goes back to check the condition and starts the next iteration.
|
number = 0 while number < 6: number += 1 if number == 3: continue print(number) |
Output:
|
1 2 4 5 6 |
Notice that 3 is missing from the output. When number equals 3, the continue statement skips the print() call and jumps back to the condition check.
When should you use continue? Use continue when you want to skip a specific iteration but keep the loop running.
The pass statement does nothing. It is a placeholder. You use it when the loop body is empty or when you want to write the logic later.
|
number = 0 while number < 5: number += 1 pass print(f"Loop finished. number = {number}") |
Output:
| Loop finished. number = 5 |
pass is useful when you are building your code structure and want to leave a section empty without causing a syntax error.'
Read Also:
Python allows you to attach an else block to a while loop. The else block runs only when the loop ends normally, meaning the condition becomes False on its own.
The else block does not run if the loop ends with a break statement.
|
number = 1 while number <= 4: print(number) number += 1 else: print("Loop completed without a break.") |
Output:
|
1 2 3 4 Loop completed without a break. |
Now let us see what happens when break is involved:
|
number = 1 while number <= 4: print(number) if number == 3: break number += 1 else: print("This will not print because break was used.") |
Output:
|
1 2 3 |
The else block did not run because the loop exited through a break. This behavior makes while-else very useful in search algorithms. You can use it to check whether a loop found what it was looking for.
Read Also: Bottle Web Framework
A nested while loop is a while loop inside another while loop. The inner loop runs completely for every single iteration of the outer loop.
|
outer = 1 while outer <= 3: inner = 1 while inner <= 3: print(f"outer={outer}, inner={inner}") inner += 1 outer += 1 |
Output:
|
outer=1, inner=1 outer=1, inner=2 outer=1, inner=3 outer=2, inner=1 outer=2, inner=2 outer=2, inner=3 outer=3, inner=1 outer=3, inner=2 outer=3, inner=3 |
A classic use case for nested while loops is printing patterns or working with 2D data structures like matrices.
Example: Simple multiplication table
|
row = 1 while row <= 5: col = 1 while col <= 5: print(f"{row * col:4}", end="") col += 1 print() row += 1 |
Output:
|
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 |
Tip: Be careful with nested loops. The time complexity grows quickly. A loop inside a loop means n x m iterations for an n-row, m-column grid.
Also Read: What is Keras?
Both loops repeat code, but they serve different purposes. Here is a clear comparison:
| Feature | While Loop | For Loop |
| Use when | You do not know the number of iterations | You know the number of iterations |
| Condition | Checks a boolean condition | Iterates over a sequence or range |
| Risk | Can become infinite if not managed | Naturally bounded |
| Best for | Input validation, retry logic, game loops | Iterating lists, strings, ranges |
While loop example:
|
# Keep asking until user gives valid input response = "" while response not in ["yes", "no"]: response = input("Answer yes or no: ") |
For loop version of the same task:
|
for i in range(5): print(i) |
A good rule of thumb: use a for loop when you have a sequence or a known count. Use a while loop when the stopping condition depends on something that changes at runtime.
Here are practical examples of where developers use while loops in real Python projects.
|
age = -1 while age < 0 or age > 120: age = int(input("Enter a valid age (0-120): ")) print(f"Your age is: {age}") |
The loop keeps asking until the user enters a valid age. You do not know how many tries it will take, so a while loop is the right choice here.
|
import time attempts = 0 max_attempts = 3 success = False while attempts < max_attempts and not success: try: # Simulating a network call print(f"Attempt {attempts + 1}: Connecting to server...") # response = requests.get("https://example.com") # Actual call success = True print("Connection successful.") except Exception as e: attempts += 1 print(f"Failed. Retrying in 2 seconds...") time.sleep(2) if not success: print("All attempts failed.") |
|
with open("data.txt", "r") as file: line = file.readline() while line: print(line.strip()) line = file.readline() |
|
health = 100 while health > 0: print(f"Player health: {health}") damage = int(input("Enter damage taken: ")) health -= damage print("Game over!") |
Also Read: The Pyramid Web Framework
Even experienced developers make these mistakes. Watch out for them.
|
# This is an infinite loop — counter never changes counter = 0 while counter < 5: print("Hello") # counter += 1 is missing! |
Always update the variable that controls your condition inside the loop body.
|
# This prints 1 to 4, not 1 to 5 number = 1 while number < 5: print(number) number += 1 |
If you want to include 5, use number <= 5.
|
# This never runs because 10 is not less than 1 number = 10 while number < 1: print(number) |
Always trace your condition before running the loop.
|
x = 5 while x = 5: # SyntaxError! Use == for comparison print(x) Use == for comparison and = for assignment. |
Also Read: Python Comments
This pattern is very common in Python programs that interact with users.
|
print("Welcome to the number guessing game!") secret = 42 guess = 0 while guess != secret: guess = int(input("Guess the number: ")) if guess < secret: print("Too low! Try again.") elif guess > secret: print("Too high! Try again.") print("Correct! You guessed it.") |
This loop will keep running until the user guesses the right number. The exit condition depends entirely on user behavior, which is exactly what while loops are designed for.
A while loop runs as long as its condition is true. You control that condition. If you do not update the condition variable or give the loop a way to exit, it will run forever. That is one of the most common mistakes beginners make.
Use a break when you need to exit early. Use continue when you want to skip just one iteration. Attach an else block when you need to know if the loop finished without hitting a break. And when you are not sure whether to use a while loop or a for loop, ask yourself one question: do I know how many times this needs to run? If yes, use a for loop. If not, then a while loop is your answer.
Now close this guide and open your editor. Write a small program. A number guessing game, a simple input validator, anything. You will learn more in 10 minutes of writing code than in an hour of reading about it.
Also Read: Convert String to Int in Python
You have a few options. The cleanest way is to update the variable your condition depends on so that it eventually becomes false. You can also use the break statement to exit the loop immediately from anywhere inside it. If a loop is stuck running in your terminal, press Ctrl + C to force it to stop.
An infinite loop is a while loop whose condition never becomes False. It runs forever unless you stop it. To avoid it, always update the variable that your condition depends on inside the loop body, or use a break statement to provide an exit point.
A for loop works best when you know how many times you need to iterate or when you are going through a sequence like a list or range. A while loop is better when the number of iterations depends on something that changes while the program runs, like user input or a network response.
Yes. The else block in a while loop runs when the condition becomes False naturally. It does not run if the loop exits through a break statement. This is useful for search algorithms where you want to know if the loop completed without finding a match.