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
condition
is 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
. count
is increased by 1 each time.- When
count
becomes 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
num
is 3,continue
skips theprint(num)
and moves to the next loop.
Summary
while
loops are great when you don't know in advance how many times to repeat.- Always make sure the condition will eventually become
False
to avoid infinite loops. - Use
break
to exit early andcontinue
to skip an iteration.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.