What is a while loop in Python?
A while loop is used to execute a block of code repeatedly as long as a specified condition is True.
Syntax:
while condition:
# code block to execute
- The
conditionis checked before each iteration. - If the condition is
True, the code block runs. - If the condition becomes
False, the loop stops.
Basic Example
count = 1
while count <= 5:
print("Count is:", count)
count += 1 # increase count by 1
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Explanation:
- The loop runs as long as
count <= 5. countis increased by 1 each time.- When
countbecomes 6, the condition isFalse, and the loop ends.
Infinite Loop Example
If the condition never becomes False, the loop runs forever:
while True:
print("This will run forever!")
To avoid this, you can use a break statement or make sure the condition eventually becomes False.
Using break in a while Loop
while True:
user_input = input("Enter 'exit' to stop: ")
if user_input == "exit":
break
print("You entered:", user_input)
This loop keeps running until the user types "exit".
➰ Using continue in a while Loop
The continue statement skips the current iteration and goes to the next one.
num = 0
while num < 5:
num += 1
if num == 3:
continue
print(num)
Output:
1
2
4
5
Explanation:
- When
numis 3,continueskips theprint(num)and moves to the next loop.
Summary
whileloops are great when you don't know in advance how many times to repeat.- Always make sure the condition will eventually become
Falseto avoid infinite loops. - Use
breakto exit early andcontinueto skip an iteration.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
