In this Python tutorial, you will learn how a while loop in Python works, how to write its syntax correctly, how to avoid infinite loops, and how to use break, continue, nested while loops, and loop conditions with clear example programs.
What is a While Loop in Python?
A Python while loop is a control flow statement that repeatedly executes a block of code as long as a given condition evaluates to True.
Before every iteration, Python checks the condition. If the condition is True, the statements inside the loop run. If the condition is False, Python stops the loop and continues with the next statement after the loop.
A while loop is useful when you do not know the exact number of repetitions in advance. For example, you may want to keep reading input until the user enters a valid value, keep processing records until a list is empty, or keep running a menu until the user chooses to exit.
Python While Loop Syntax
The syntax of Python while loop is shown below.
while condition :
statement(s)
The condition is a Boolean expression, or an expression that Python can evaluate as truthy or falsy. The statement(s) inside the loop must be indented. Indentation is important because Python uses indentation to identify the body of the loop.
In most while loops, one or more variables used in the condition must be updated inside the loop. Without that update, the condition may never become False, which can create an infinite loop.
How Python While Loop Works Step by Step
- Python evaluates the while loop condition.
- If the condition is
True, Python enters the loop body. - The statements inside the loop body are executed in order.
- After the loop body finishes, Python goes back and checks the condition again.
- This process continues until the condition becomes
False. - When the condition is
False, Python exits the loop.
Python While Loop Flowchart
The following flowchart shows the flow of execution of a while loop. The loop is depicted in blue lines.
Python While Loop Example to Print Multiples of 3
In the following program, we use a while loop to print multiples of 3 from 3 to 30.
Example.py
i=1
while i < 11:
print(3*i)
i=i+1
Output
3
6
9
12
15
18
21
24
27
30
Here, i starts with the value 1. During each iteration, the program prints 3*i and then increases i by 1. When i becomes 11, the condition i < 11 becomes False, so the loop stops.
Python While Loop with a Counter Variable
A counter variable is commonly used in a Python while loop. The counter usually has three parts: initialization before the loop, condition checking in the while statement, and update inside the loop.
count = 1
while count <= 5:
print("Count is", count)
count += 1
Output
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
This pattern is useful when you want a while loop to run a known number of times. Even though a For Loop statement is often preferred for known ranges, a while loop can still be used when the counter update depends on some condition inside the loop.
Python Nested While Loop
The body of while loop consists of statements. And these statements could be another while loop, If statement, If-Else statement or For Loop statement or any valid Python statement.
Print Star Pattern using Nested While Loop in Python
In the following example, we write a while loop inside another while loop. This is called a nested while loop. Using this nested while loop, we print a star pattern.
Example.py
i=1
while i < 11:
j = 0
while j < i:
print('*',end='')
j=j+1
print()
i=i+1
Output
*
**
***
****
*****
******
*******
********
*********
**********
In this program, the outer while loop controls the number of rows. The inner while loop controls how many stars are printed in each row.
More about Python Nested While Loop.
Python While Loop with Break Statement
Python Break statement can be used inside a looping statement to break the loop even before condition becomes False.
In the following example, we have a while loop statement. The while loop has a break statements that executes conditionally when i becomes 7. And inside this if-statement we have break statement. This break statement breaks the while loop.
Example.py
i = 1
while i <= 100 :
print(i)
if i == 7 :
break
i += 1
Output
1
2
3
4
5
6
7
The condition i <= 100 could allow the loop to continue up to 100, but the break statement exits the loop when i is equal to 7. The break statement is useful when a loop should stop immediately after a required condition is met.
More about Python While Loop with Break Statement.
Python While Loop with Continue Statement
Python Continue statement can be used to skip the execution of further statements in while loop body and continue with next iteration of while loop.
In this example, we shall write a Python program with while loop to print numbers from 1 to 20. But, when we get an odd number, we will continue the loop with next iterations.
Example.py
i = 0
while i <= 20 :
i += 1
if i % 2 == 1 :
continue
print(i)
Make sure that you update the control variables participating in the while loop condition, before you execute the continue statement.
Output
2
4
6
8
10
12
14
16
18
20
In this program, continue skips the print(i) statement for odd numbers. Therefore, only even numbers are printed.
More about Python While Loop with Continue Statement.
Python While Loop with Else Block
Python also allows an else block with a while loop. The else block runs when the while loop condition becomes False. It does not run if the loop is stopped using break.
number = 1
while number <= 3:
print(number)
number += 1
else:
print("Loop finished")
Output
1
2
3
Loop finished
Here, the loop ends normally after number becomes 4. Since the condition becomes False naturally and no break statement stops the loop, the else block is executed.
Python Infinite While Loop
Infinite while loop is a loop in which the condition is always True and never comes out of the loop.
Example.py
while True:
print("hello")
Output
hello
hello
hello
hello
An infinite while loop may be intentional in programs such as servers, menu-driven applications, or event loops. In beginner programs, it is often accidental and happens because the loop condition never becomes False.
More about Python Infinite While Loop.
How to Stop an Infinite While Loop in Python Safely
To avoid an accidental infinite loop, check that the loop condition can change during execution. Usually, this means updating the counter, changing a flag variable, removing an item from a collection, or using break when a stopping condition is reached.
attempts = 0
while True:
attempts += 1
print("Attempt", attempts)
if attempts == 3:
break
Output
Attempt 1
Attempt 2
Attempt 3
In this example, while True creates an infinite loop structure, but the break statement provides a clear exit condition.
When to Use While Loop Instead of For Loop in Python
Use a while loop when the loop should continue until a condition changes, especially when the number of iterations is not known before the loop starts.
| Requirement | Prefer | Reason |
|---|---|---|
| Repeat while a condition is true | while loop | The number of iterations may not be known in advance. |
| Loop through a range, list, tuple, string, or dictionary | for loop | The sequence is already known. |
| Build a menu that runs until the user exits | while loop | The program waits for a particular user choice. |
| Repeat exactly 10 times | for loop | A fixed range is simpler and clearer. |
Common Mistakes in Python While Loop Programs
- Forgetting to update the loop variable: If the variable in the condition never changes, the loop may run forever.
- Writing the wrong comparison operator: For example, using
<instead of<=can change the final value processed by the loop. - Placing
continuebefore the update: This can skip the update step and cause an infinite loop. - Incorrect indentation: Python requires the loop body to be indented consistently.
- Using while loop when for loop is clearer: If you are looping over a known sequence, a for loop is usually easier to read.
Python Programs Based on While Loop
Following are references to some of the tutorials that use while loop in different scenarios.
Python While Loop Editorial QA Checklist
- Does every while loop example show how the condition eventually becomes
Falseor howbreakexits the loop? - Are output blocks marked as output and not as Python syntax?
- Does each example explain the role of the counter, condition, and update statement?
- Are
break,continue, nested while loop, and infinite while loop examples separated clearly? - Does the tutorial warn beginners about accidental infinite loops and indentation errors?
FAQs on While Loop in Python
What is a while loop in Python with example?
A while loop in Python repeatedly runs a block of code while its condition is True. For example, while i <= 5: can be used to print numbers from 1 to 5 when i is increased inside the loop.
Why do we use while loop in Python?
We use a while loop in Python when we want to repeat statements until a condition changes. It is useful when the exact number of repetitions is not known before the loop starts.
What happens if the while loop condition is always True?
If the while loop condition is always True, the loop becomes an infinite loop. It will continue running until the program is stopped externally or until a break statement exits the loop.
Can we use else with while loop in Python?
Yes. Python supports an else block with a while loop. The else block runs when the loop condition becomes False, but it does not run if the loop exits using break.
What is the difference between break and continue in a Python while loop?
In a Python while loop, break exits the loop completely, while continue skips the remaining statements in the current iteration and moves to the next condition check.
Summary of Python While Loop
In this Python Tutorial, we learned what a while loop is, how its condition controls repeated execution, how to use while loop syntax, and how to work with nested while loops, break, continue, else, and infinite while loops. A good while loop should have a clear condition and a clear way for that condition to become False, unless the loop is intentionally controlled using break.
TutorialKart.com