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 is False
, 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 the print(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 and continue
to skip an iteration.