Introduction
Loops are one of the fundamental concepts in programming that allow a block of code to execute repeatedly until a specified condition is met.
Python provides two main types of loops:
- for loop
- while loop
while loop is used when the number of iterations is not known in advance. The while loop continues executing as long as a specified condition remains true.
For example, an ATM machine keeps displaying options until the user chooses to exit.
What is Python While Loop?
A Python while loop repeatedly executes a block of code as long as a specified condition evaluates to True.
The condition is checked before each iteration. If the condition becomes False, the loop stops.
Example:
count = 1
while count <= 5:
print(count)
count += 1
Output:
2
3
4
5
In this example:
- The loop starts with count = 1.
- The condition count <= 5 is checked.
- The loop executes while the condition is true.
- After each iteration, count increases by 1.
- The loop stops when count becomes 6.
Why Use a While Loop?
A while loop is useful when:
- The number of iterations is unknown.
- The loop depends on user input.
- A program must continue until a condition changes.
- Continuous monitoring is required.
Syntax
The basic syntax of a while loop is:
while condition:
# code block
Syntax Breakdown
- while is a Python keyword.
- condition is evaluated before each iteration.
- The code block executes if the condition is true.
- The loop ends when the condition becomes false.
Flow of Execution
A while loop follows these steps:
- Evaluate the condition.
- If true, execute the loop body.
- Return to the condition.
- Repeat until the condition becomes false.
- Exit the loop.
Simple While Loop Example
number = 1
while number <= 3:
print(number)
number += 1
Output:
2
3
The loop executes three times because the condition remains true during those iterations.
Display Numbers from 1 to 10
count = 1
while count <= 10:
print(count)
count += 1
Output:
2
3
4
5
6
7
8
9
10
Display Even Numbers
number = 2
while number <= 10:
print(number)
number += 2
Output:
4
6
8
10
Countdown Example
count = 5
while count > 0:
print(count)
count -= 1
print("Blast Off!")
Output:
4
3
2
1
Blast Off!
Taking User Input with While Loop
password = ""
while password != "python123":
password = input("Enter Password: ")
print("Access Granted")
Output:
Enter Password: test
Enter Password: python123
Access Granted
This is a common use of while loops in authentication systems.
Infinite While Loop
A while loop becomes infinite when its condition never becomes false.
Example:
while True:
print("Running...")
This loop will continue forever unless interrupted.
Output:
Running…
Running…
…
While Loop with Break Statement
The break statement immediately exits the loop.
Example:
count = 1
while True:
print(count)
if count == 5:
break
count += 1
Output:
2
3
4
5
The loop stops when count reaches 5.
While Loop with Continue Statement
The continue statement skips the current iteration.
Example:
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
Output:
2
4
5
The number 3 is skipped.
While Loop with Else
Python allows an optional else block with while loops.
Example:
count = 1
while count <= 3:
print(count)
count += 1
else:
print("Loop Finished")
Output:
2
3
Loop Finished
The else block executes when the loop ends normally.
Nested While Loop
A while loop can be placed inside another while loop.
Example:
i = 1
while i <= 3:
j = 1
while j <= 2:
print(i, j)
j += 1
i += 1
Output:
1 2
2 1
2 2
3 1
3 2
Nested loops are useful for tables, patterns, and matrix operations.
Example: Multiplication Table
Example:
number = 5
count = 1
while count <= 10:
print(number * count)
count += 1
Output:
10
15
20
25
30
35
40
45
50
Example: Calculate Sum of Numbers
count = 1
total = 0
while count <= 5:
total += count
count += 1
print(total)
Output:
Real-Life Examples:
1. ATM Machine
balance = 10000
while balance > 0:
print("Current Balance:", balance)
withdraw = 2000
balance -= withdraw
if balance <= 0:
print("Account Empty")
Output:
Current Balance: 8000
Current Balance: 6000
Current Balance: 4000
Current Balance: 2000
Account Empty
ATM systems often use loops to process transactions continuously.
2. Login System
username = ""
while username != "admin":
username = input("Enter Username: ")
print("Login Successful")
Output:
Enter Username: guest
Enter Username: admin
Login Successful
Login forms commonly use this logic.
3. Online Quiz
score = 0
question = 1
while question <= 5:
score += 1
question += 1
print("Final Score:", score)
Output:
Many educational applications use loops to process quiz questions.
4. File Download Progress
progress = 0
while progress < 100:
progress += 20
print("Downloading:", progress, "%")
Output:
Downloading: 40 %
Downloading: 60 %
Downloading: 80 %
Downloading: 100 %
Download managers often track progress using loops.
Advantages of While Loop
1. Flexible Iteration
The loop continues until a condition changes.
2. Ideal for Unknown Iterations
Useful when the number of repetitions is not known beforehand.
3. Supports Continuous Processes
Excellent for monitoring and interactive programs.
4. Easy Input Validation
Can repeatedly request valid user input.
5. Works with Break and Continue
Provides additional control over loop execution.
Common Mistakes
1. Forgetting to Update the Variable
Incorrect:
count = 1
while count <= 5:
print(count)
Output:
The variable never changes.
Correct:
count += 1
2. Missing Colon
Incorrect:
while count <= 5
print(count)
Output:
Correct:
while count <= 5:
print(count)
3. Incorrect Indentation
Incorrect:
while count <= 5:
print(count)
Output:
Correct:
while count <= 5:
print(count)
4. Creating Unintentional Infinite Loops
Incorrect:
while True:
print("Hello")
Without a break statement, this loop never ends.
5. Wrong Condition
Incorrect:
count = 10
while count < 5:
print(count)
Output:
The condition is false from the beginning.
Best Practices
1. Use Meaningful Variable Names
attempts = 0
Instead of:
a = 0
2. Avoid Infinite Loops
Always ensure the condition can become false.
3. Use Break When Necessary
if user_choice == "exit":
break
4. Keep Conditions Simple
Readable conditions improve maintainability.
5. Validate User Input
While loops are excellent for input validation.
Conclusion
The Python while loop is a powerful control flow statement that allows code to execute repeatedly as long as a specified condition remains true. Unlike a for loop, which is generally used when the number of iterations is known, a while loop is ideal for situations where the number of repetitions depends on changing conditions or user input.
Python While loop – Interview Questions
Q 1: What is a while loop in Python?
Q 2: When is a while loop used?
Q 3: What happens if the condition never becomes false?
Q 4: Can a while loop run zero times?
Q 5: Which statement is commonly used to control a while loop?
Python While loop – Objective Questions (MCQs)
Q1. Which keyword is used to create a while loop in Python?
Q2. What will be the output of the following code?
i = 1
while i < 4:
print(i)
i += 1;
Q3. The condition inside a while loop is checked:
Q4. What will happen if the condition in a while loop never becomes False?
Q5. Which statement can be used to terminate a while loop early?