When performing repetitive tasks in Python, the for loop is suitable when you know the “number of elements in a list” or a “specific number of iterations.” On the other hand, there are cases where the number of iterations is not fixed, but you want to “continue processing as long as a certain condition is met.” For example, “wait until the user presses the exit button” or “run until the battery runs out.”
For such state-based repetition, we use the while loop. This article explains the basic syntax of the while loop and points to be aware of when using it.
Basic Syntax of while Loop
The while loop repeatedly executes the processing inside the block as long as the condition specified immediately after it is True.
Syntax:
while condition:
# Process to be repeated while the condition is True
# (Indented block)
The flow of processing is as follows:
- Evaluate the condition.
- If True, execute the processing inside the block.
- Evaluate the condition again.
- If True, execute again. If False, end the loop and proceed to the next line.
Specific Usage Example
As an example, let’s create a program that continues to operate until a device’s battery level falls below a certain value.
# Battery level (Initial value 100%)
current_battery = 100
# Continue loop while battery is greater than 20%
while current_battery > 20:
print(f"Battery: {current_battery}% - Running normally")
# Consume 25% battery per process
current_battery -= 25
# Process after loop ends
print(f"Battery: {current_battery}% - Switching to Low Power Mode.")
Output:
Battery: 100% - Running normally
Battery: 75% - Running normally
Battery: 50% - Running normally
Battery: 25% - Running normally
Battery: 0% - Switching to Low Power Mode.
In this example, the loop runs as long as current_battery satisfies the condition (> 20). When it becomes 0 in the next step, the condition becomes False, the loop exits, and the final message is displayed.
Important Note: Infinite Loops
The most important thing to watch out for when using while loops is “Infinite Loops.” If the condition remains True forever and never becomes False, the program will never exit that loop (causing it to freeze or crash).
Example of an Infinite Loop (Be Careful):
count = 10
# Since count never decreases, it stays greater than 0 forever
while count > 0:
print("This process never ends")
# Forgot to write the code to decrease count here!
When writing a while loop, always check that you have included “processing inside the loop that will eventually change the condition to False (such as updating a variable).”
Summary
- Write it in the format:
while condition:. - Repeats the process as long as the condition is
True. - Suitable when the number of iterations is unknown and you want to loop based on a specific “state.”
- You must strictly ensure variables are updated inside the loop to avoid falling into an “Infinite Loop” where the condition never becomes
False.
