For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
Loops are essential when you need to run a set of instructions repeatedly. One of the most commonly used loops in Python is the while loop. The while loop in Python runs a block of code as long as a given condition is true.
In this article, we will explore how this loop works with real-world examples, from basic to advanced. We will also understand when and why to use it over other loops like for. You will also learn how the loop handles infinite conditions and how it differs from the for loop in Python. Whether you're a beginner or someone looking to brush up your Python basics, this article will help you use the while loop efficiently and correctly.
Pursue our Software Engineering courses to get hands-on experience!
The while loop in Python is used to execute a block of code repeatedly as long as a specific condition remains true. Unlike a for loop, which runs for a predefined number of times, a while loop continues until the given condition becomes false.
This makes it ideal for scenarios where the number of iterations isn’t known in advance. You can use it for checking sensor values, reading files until EOF, or repeating user input requests until valid data is entered.
Before writing real-world examples, it's important to understand the correct syntax of a while loop in Python. The structure is simple and easy to remember. The loop starts with the keyword while, followed by a condition. As long as the condition is True, the loop body will keep executing.
Below is the general syntax with a short example to help you understand better.
while condition:
# block of code
Take your skills to the next level with these top programs:
Now let’s see a working example that uses this syntax.
Example: Print Numbers from 1 to 3
# Initialize a counter variable
count = 1
# Loop continues while count is less than or equal to 5
while count <= 5:
print("Current count:", count) # Print current value
count += 1 # Increment the counter
Output:
Current count: 1
Current count: 2
Current count: 3
Current count: 4
Current count: 5
Explanation:
This is the basic structure of how a while loop works in Python. It is simple but powerful and can be adapted for complex tasks too.
Must Explore: Nested for loop in Python
Let’s look at different examples of the while loop in Python to understand how it works in real scenarios. We will begin with a basic example and move on to intermediate and advanced use cases.
This example demonstrates how to use a while loop to print even numbers within a range. It uses a simple condition and an increment statement.
# Initialize a counter variable
count = 1
# Loop continues while count is less than or equal to 5
while count <= 5:
print("Current count:", count) # Print current value
count += 1 # Increment the counter
Output:
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10
Explanation:
This example shows how to keep asking the user for input until they enter the correct password. This is a common use case where you don’t know how many tries the user might take.
# Correct password to match
correct_password = "python123"
# Initialize user input
user_input = ""
# Keep prompting until input matches the correct password
while user_input != correct_password:
user_input = input("Enter the password: ")
print("Access Granted!")
Output:
Enter the password: python12
Enter the password: python 123
Enter the password: python123
Access Granted!
Explanation:
Also read the Top 43 Pattern Programs in Python to Master Loops and Recursion article!
This example uses a while loop to simulate a countdown timer. It also uses the time module to pause execution between iterations.
import time # Importing time module
# Start countdown from 5
countdown = 5
# Loop until countdown reaches 0
while countdown > 0:
print("Timer:", countdown)
time.sleep(1) # Pause for 1 second
countdown -= 1 # Decrement the counter
print("Time's up!")
Output:
Timer: 5
Timer: 4
Timer: 3
Timer: 2
Timer: 1
Time's up!
Explanation:
An infinite while loop in Python is a loop that never stops running unless you explicitly break it. This happens when the loop condition always evaluates to True. These loops are useful in cases like waiting for user input, running servers, or background tasks.
Let’s see how to create one and how to control it using a break statement.
Example: Infinite Loop That Waits for a Keyword to Exit
# Start an infinite loop
while True:
# Ask the user to enter a command
user_input = input("Type 'exit' to stop the loop: ")
# Check if the input is 'exit'
if user_input.lower() == 'exit':
print("Exiting the loop.")
break # Exit the loop
else:
print("You typed:", user_input)
Output:
Type 'exit' to stop the loop: hello
You typed: hello
Type 'exit' to stop the loop: python
You typed: python
Type 'exit' to stop the loop: exit
Exiting the loop.
Explanation:
Note:
If you don’t include a break statement or a condition that eventually turns False, the loop will run forever and may freeze your program.
Best Practices:
Also explore Python's do-while Loop article!
In Python, the continue statement is used inside a while loop to skip the current iteration and move to the next one. This helps in cases where you want to ignore certain values or conditions without exiting the loop entirely.
Let’s understand this with a simple and practical example.
Example: Print Numbers from 1 to 10 but Skip Multiples of 3
# Start counting from 1
num = 1
# Loop until num exceeds 10
while num <= 10:
# Skip numbers divisible by 3
if num % 3 == 0:
num += 1 # Increment before continue to avoid infinite loop
continue # Skip printing this number
print("Number:", num)
num += 1 # Increment num for the next iteration
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Number: 7
Number: 8
Number: 10
Explanation:
Using continue helps you control which iterations to process and which to skip. It improves code clarity by avoiding nested conditions inside the while loop in Python.
In Python, the break statement is used inside a while loop to stop the loop immediately, regardless of the loop’s original condition. This lets you exit the loop when a specific event or condition occurs.
Using break helps you control the flow more precisely, especially when you want to terminate the loop early.
Example: Stop the Loop When Number Reaches 5
# Initialize the counter
num = 1
# Start the while loop
while True:
print("Current number:", num)
# Stop the loop when num reaches 5
if num == 5:
print("Reached 5, exiting the loop.")
break # Exit the loop immediately
num += 1 # Increment the counter
Output:
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5
Reached 5, exiting the loop.
Explanation:
The pass statement in Python acts as a placeholder inside a while loop. It does nothing but allows the loop to run without errors when no action is needed in a particular part of the code.
This is helpful when you plan to add code later or want to create a loop that intentionally does nothing in some cases.
Example: Using Pass to Create an Empty While Loop That Runs Three Times
# Initialize the counter
count = 0
# Run the loop while count is less than 3
while count < 3:
pass # Placeholder: no action is performed here
# Increment the counter
count += 1
print("Loop finished after 3 iterations.")
Output:
Loop finished after 3 iterations.
Explanation:
Must Read: Break Pass and Continue Statement in Python
In Python, a while loop can have an optional else block. The else block executes only when the while loop condition becomes false. However, if the loop exits due to a break statement, the else block is skipped.
This feature allows you to run specific code after the loop completes normally.
Example: Using Else with While Loop to Confirm Completion
# Initialize counter
num = 1
# Loop while num is less than or equal to 5
while num <= 5:
print("Number:", num)
num += 1
else:
print("Loop finished without interruption.")
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Loop finished without interruption.
Explanation:
Also read the Reverse String in Python article!
The while loop in Python is best suited for scenarios where you want to repeat a block of code until a certain condition changes. Unlike for loops, which iterate over sequences, while loops work well when the number of iterations is unknown beforehand.
Consider an example where you keep doubling a number until it exceeds a limit.
Example: Double a Number Until It Becomes Greater Than 100
# Initialize the number
number = 1
# Loop until number is greater than 100
while number <= 100:
print("Current number:", number)
# Double the number each time
number *= 2
print("Loop ended as the number exceeded 100.")
Output:
Current number: 1
Current number: 2
Current number: 4
Current number: 8
Current number: 16
Current number: 32
Current number: 64
Loop ended as the number exceeded 100.
Explanation:
In short, use Python While Loop when:
Both while and for loops allow repetition in Python, but they serve different purposes. Understanding their differences helps you choose the right loop based on the problem you want to solve.
Below is a detailed comparison between the two loops:
Aspect | While Loop | For Loop |
Purpose | Runs as long as a condition remains true. | Iterates over a sequence or iterable directly. |
Control | Condition checked before each iteration. | Iterates through items or a range automatically. |
Use Case | When the number of iterations is unknown. | When the number of iterations is known or fixed. |
Syntax | while condition: # code | for item in iterable: # code |
Possibility of Infinite Loop | High if the condition never becomes false. | Low, since it iterates over a finite iterable. |
Modification during Loop | You manually update the condition variable inside the loop. | Loop variable updates automatically each iteration. |
When to use | When loop continuation depends on dynamic conditions. | When looping through elements or fixed counts. |
Example | while x < 5: x += 1 | for x in range(5): print(x) |
Must read the Exception Handling in Python article!
In this article, we explored the while loop in Python, a fundamental tool for repeating code based on conditions. We learned how the while loop runs until its condition becomes false. This makes it powerful for tasks where the number of repetitions is not fixed.
We also examined various practical examples, from basic to advanced levels, including how to use control statements like break, continue, and pass within the while loop. Understanding these helps you control loop execution efficiently.
The primary advantage of a while loop in Python is its ability to run based on a condition rather than a fixed count. This flexibility allows you to repeat code until a specific dynamic event occurs, making it ideal for situations where the number of iterations is unknown.
Yes, you can use multiple conditions in a while loop using logical operators like and, or, and not. This lets you create complex criteria for loop execution. For example, while x < 10 and y != 0: runs only when both conditions hold true.
While loops repeat code using iteration, whereas recursion repeats by calling a function within itself. The while loop is often more memory-efficient and easier to debug. Recursion is better for problems naturally defined by smaller subproblems, like tree traversal.
Yes. When a while loop completes normally without hitting a break statement, the else block runs. If the loop breaks early, the else block is skipped. This feature helps detect whether a loop ended naturally or was interrupted.
To prevent infinite loops, ensure the loop’s condition eventually becomes false. You should update variables involved in the condition inside the loop. Also, using timeout counters or input validation can help stop the loop if unexpected behavior occurs.
Absolutely. You can nest a while loop inside another while loop or a for loop. Nested loops are useful for working with multi-dimensional data or complex iteration patterns. However, keep track of each loop’s condition to avoid logical errors or infinite loops.
If the condition in a while loop in Python is false at the start, the loop’s body never executes. The program immediately moves to the next statement after the loop. This behavior is different from a do-while loop found in some other languages.
No, the while loop itself does not iterate over items like a for loop. However, you can manually control the index or pointer inside the loop to traverse a list or iterable. For example, use an index variable and increment it in each iteration.
A while loop is perfect for input validation because it can repeatedly ask the user until valid data is entered. For instance, use a loop with a condition checking the input format or range and continue prompting the user until the input meets requirements.
For loops are generally faster for iterating over sequences since Python optimizes them internally. While loops offer more flexibility but may require extra care to manage conditions. For most cases, the difference is negligible, but for large data, using for loops is often preferable.
The break statement immediately ends the loop, useful when you want to stop early based on a condition. The continue statement skips the rest of the current iteration and moves to the next one. Together, they make the while loop in Python more powerful and adaptable.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.