Python While Loop
Repeating Code Based on a Condition: Understanding the While Loop
In Python, the while loop is used to repeatedly execute a block of code as long as a specific condition remains true. It's ideal for situations where you don't know in advance how many times you need to loop, and the repetition depends entirely on whether a condition is met.
While the for
loop iterates over a fixed sequence, the while
loop keeps going as long as its condition is True
. This makes it useful for tasks like waiting for user input, processing data until a certain state is reached, or implementing retry logic.
What Is a While Loop?
A while loop executes a block of code as long as its controlling condition
is true. The condition is evaluated before each iteration of the loop.
If the condition is initially false, the code block inside the loop will not be executed at all. If the condition remains true, the loop will continue to run. It's crucial that something within the loop changes the state related to the condition, so that the condition will eventually become false; otherwise, you'll create an infinite loop.
Syntax of the While Loop
The basic syntax of a while
loop is:
while condition:
# code block to be executed as long as the condition is true
while
: The keyword that starts a while loop.condition
: An expression that evaluates to eitherTrue
orFalse
. The loop continues as long as this isTrue
.:
: Marks the end of thewhile
statement header.- Indented Code Block: The code that runs repeatedly. It must be indented.
A Simple Example
Let's look at a simple example that uses a while
loop to count from 0 up to 4:
count = 0
while count < 5:
print(count)
count += 1 # Important: update the condition variable!
Output:
0
1
2
3
4
Here, count < 5
is the condition. The loop starts with count
at 0. As long as count
is less than 5, the loop prints the current count
and then adds 1 to it (count += 1
). This ensures that eventually count
reaches 5, the condition count < 5
becomes false, and the loop stops.
Infinite Loops
An infinite loop occurs when the condition of a while
loop never becomes false. This can happen if you forget to update the variable(s) involved in the condition or if the condition is always inherently true (like while True:
).
# Caution: This is an infinite loop!
# while True:
# print("This will print forever!")
# To stop this, you usually need to interrupt the program (e.g., press Ctrl+C in the terminal).
# Another infinite loop example - forgets to increment count
# count = 0
# while count < 5:
# print(count) # count will always be 0, condition never false
Always make sure there is logic inside your while
loop that will eventually cause the condition to become false.
Using break
and continue
Like for
loops, while
loops can use break
and continue
to alter their flow.
break
: Immediately exits the loop, regardless of the condition.continue
: Skips the rest of the current iteration's code block and jumps back to the top of the loop to re-evaluate the condition.
Example with break
:
secret_word = "python"
user_guess = ""
while True: # Loop indefinitely until break is hit
user_guess = input("Enter the secret word: ").lower()
if user_guess == secret_word:
print("Correct! You guessed the word.")
break # Exit the loop
else:
print("Incorrect guess. Try again.")
In this example, the loop condition is always True
, but the loop stops only when the break
statement is executed after a correct guess.
Example with continue
:
number = 0
while number < 10:
number += 1
if number % 2 != 0: # If the number is odd
continue # Skip the print statement below
print(f"Even number: {number}")
Output:
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Even number: 10
When number
is odd, continue
is executed, and the print
statement for that iteration is skipped. The loop then proceeds to the next value of number
.
The else
Clause with While Loops
A while
loop can also have an optional else
block. The code in the else
block is executed only if the loop completes normally, meaning the condition evaluated to False
. If the loop is exited prematurely by a break
statement, the else
block is skipped.
Example where else
runs:
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop finished normally (count is no longer less than 3).")
Output:
0
1
2
Loop finished normally (count is no longer less than 3).
The loop condition count < 3
eventually became false, so the else
block ran.
Example where else
does NOT run:
count = 0
while count < 10: # Condition would eventually be false, but we break first
if count == 2:
print("Breaking loop when count is 2.")
break
print(count)
count += 1
else:
print("Loop finished normally.") # This will not run
Output:
0
1
Breaking loop when count is 2.
The loop was exited by break
, so the else
block was skipped.
Common Use Cases for While Loops
while
loops are particularly useful when:
- The number of repetitions is not fixed before the loop starts.
- You need to repeat an action until a specific condition changes (e.g., reading from a file until the end, retrying a network request until it succeeds).
- You need to validate user input, repeatedly asking until valid data is provided.
For iterating over the elements of a list, string, or other collection where you know the items you need to process, a for
loop is usually more appropriate and readable.
Summary
- The
while
loop repeats a block of code as long as its condition isTrue
. - The condition is checked before each iteration.
- Ensure the condition will eventually become
False
to avoid infinite loops. - Use
break
to exit the loop immediately. - Use
continue
to skip the current iteration and re-check the condition. - The
else
block runs only if the loop completes normally. while
loops are best when the number of iterations is unknown and depends on a dynamic condition.
Mastering the while
loop gives you another powerful tool for controlling the flow of your Python programs.