Python While Loop
The while Loop in Python
The while
loop is used to repeat a block of code as long as a specified condition is true. Unlike the for
loop, which iterates over a sequence, the while
loop focuses purely on the condition—it keeps looping until that condition becomes false.
Syntax of the while Loop
Here's the basic structure:
while condition:
code_block
condition
: An expression that is evaluated before each iteration.code_block
: The set of instructions that will run repeatedly as long as the condition is true.
A Simple Example
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
This loop prints numbers from 0
to 4
. Each time through the loop, the condition count < 5
is checked. Once count
reaches 5
, the condition becomes false and the loop stops.
Infinite Loops
If the condition never becomes false, the loop will run forever. This is called an infinite loop.
while True:
print("This will run forever!")
To stop an infinite loop during testing, you can use Ctrl + C
or manually interrupt execution.
Breaking Out of a Loop
You can exit a while
loop before the condition becomes false by using the break
statement:
while True:
user_input = input("Type 'exit' to stop: ")
if user_input == "exit":
break
Output (example):
Type 'exit' to stop: hello
Type 'exit' to stop: test
Type 'exit' to stop: exit
The loop ends only when the user types "exit"
.
Using continue to Skip Iterations
The continue
statement skips the current iteration and goes back to re-check the condition:
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
Output:
1
2
4
5
The number 3
is skipped because continue
causes the loop to immediately move to the next iteration.
Validating Input with while
A common use case for while
is validating user input:
password = ""
while password != "secret":
password = input("Enter the password: ")
print("Access granted")
This keeps asking the user for the correct password until they provide "secret"
.
The else Clause in while
Just like with for
, a while
loop can have an else
clause. It runs only if the loop finishes normally (not interrupted by break
):
x = 0
while x < 3:
print(x)
x += 1
else:
print("Loop completed")
Output:
0
1
2
Loop completed
But if you break out of the loop:
x = 0
while x < 3:
if x == 1:
break
print(x)
x += 1
else:
print("Loop completed")
Output:
0
The else
block does not execute because the loop was interrupted.
Summary
- The
while
loop repeats code as long as a condition is true. - Make sure the condition eventually becomes false—otherwise, you'll create an infinite loop.
- Use
break
to exit early, andcontinue
to skip parts of the loop. - The
else
clause runs if the loop completes normally. while
is especially useful when you don’t know in advance how many times to repeat a task (like user input validation).
Use while
when the repetition depends on dynamic conditions, not on fixed sequences.
Continue Learning
Python Variables
Popular
### Understanding Variables and Literals in Python Variables and literals are the foundation of any
Personalized Recommendations
Log in to get more relevant recommendations based on your reading history.