A while loop in Python is used to execute a block of code repeatedly as long as a given condition is true. The loop checks the condition before executing the code block, and if the condition evaluates to True, the loop will continue running. If the condition becomes False, the loop terminates, and the program proceeds to the next statement.

Table of Contents
- What is a While Loop?
- Syntax of While Loop
- Example of a Simple While Loop
- Infinite While Loops
- Breaking Out of a While Loop
- Using the
elseStatement with While Loops - Common Pitfalls with While Loops
- Mini-Project: Guess the Number Game
- Interview Questions and Answers (Google, Amazon, TCS, Infosys, Zoho)
1. What is a While Loop?
A while loop repeats a block of code as long as a specified condition is True. This makes it ideal for situations where the number of iterations is not known beforehand but the loop needs to continue until a certain condition is met.
2. Syntax of While Loop
The basic syntax of a while loop is:
while condition:
# Code to execute as long as the condition is True
condition: An expression that is checked before each iteration of the loop. If it evaluates toTrue, the loop continues.- Code block: The block of code to be executed repeatedly as long as the condition is
True.
3. Example of a Simple While Loop
Let’s look at a basic example that prints numbers from 1 to 5 using a while loop.
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Here:
- The condition is
i <= 5. - The loop runs while the value of
iis less than or equal to 5. - After each iteration,
iis incremented by 1.
4. Infinite While Loops
A common pitfall of while loops is creating an infinite loop. This happens when the condition never becomes False.
Example of an Infinite Loop:
while True:
print("This loop will run forever.")
To stop such loops, you’ll need to use break or interrupt the execution manually.
5. Breaking Out of a While Loop
You can use the break statement inside a while loop to exit the loop prematurely, even if the condition has not yet become False.
Example:
i = 1
while i <= 5:
if i == 3:
break
print(i)
i += 1
Output:
1
2
Here, the loop stops when i becomes 3 because of the break statement.
6. Using the else Statement with While Loops
In Python, a while loop can also have an else block. The code inside the else block will execute only if the loop terminates without encountering a break statement.
Example:
i = 1
while i <= 5:
print(i)
i += 1
else:
print("Loop finished successfully!")
Output:
1
2
3
4
5
Loop finished successfully!
Here, the else block runs after the loop finishes because no break was encountered.
7. Common Pitfalls with While Loops
- Infinite loops: Always ensure that the loop condition will eventually become
False. - Modifying the loop variable incorrectly: If the loop variable isn’t updated properly, the loop can run indefinitely.
- Not using
breakcorrectly: Ensure thebreakstatement is used when you want to exit the loop under specific conditions.
8. Mini-Project: Guess the Number Game
In this mini-project, we’ll create a simple Guess the Number game where the user has to guess a randomly generated number between 1 and 10.
Objective:
The program will:
- Generate a random number between 1 and 10.
- Ask the user to guess the number.
- Keep asking for guesses until the user guesses correctly.
import random
def guess_number():
number = random.randint(1, 10)
guess = None
while guess != number:
guess = int(input("Guess the number between 1 and 10: "))
if guess < number:
print("Too low! Try again.")
elif guess > number:
print("Too high! Try again.")
else:
print(f"Correct! The number was {number}. You guessed it!")
guess_number()
Sample Output:
Guess the number between 1 and 10: 5
Too low! Try again.
Guess the number between 1 and 10: 8
Too high! Try again.
Guess the number between 1 and 10: 7
Correct! The number was 7. You guessed it!
Interview Questions and Answers
Q: What is the difference between a while loop and a for loop in Python?
A: A for loop is generally used when the number of iterations is known, such as when iterating through a sequence. A while loop is used when the number of iterations is not known and depends on a condition.
Amazon
Q: How do you avoid infinite loops when using a while loop?
A: Ensure that the loop condition eventually becomes False, and update the loop variable correctly within the loop. You can also use a break statement to exit the loop early if needed.
TCS
Q: Can you use a while loop with multiple conditions?
A: Yes, you can combine conditions using logical operators like and, or, or not in the loop condition:
while x < 10 and y < 20:
# Loop code
Infosys
Q: How do you handle cases where a while loop needs to exit early?
A: Use the break statement to exit the loop prematurely when a specific condition is met.
Zoho
Q: Can you have an else block in a while loop?
A: Yes, the else block executes when the while loop terminates without encountering a break statement.
While-Loop
Question
Your answer:
Correct answer:
Your Answers