Python While Loop: Syntax, Usage, and Examples
How to Use the While Loop in Python
# Execute these statements as long as the condition is true
statement(s)
- while: The keyword to initiate the while loop
- condition: A boolean expression that the while loop evaluates before each iteration. If the expression evaluates to True, the loop's body executes. As soon as the expression evaluates to False, the loop terminates.
- statement(s): Python statements to execute as long as the condition evaluates to True
When to Use the While Loop in Python
Examples of While Loops in Python
User Input Validation
while not username:
username_input = input("Enter a valid username: ")
if len(username_input) > 4:
username = username_input
Main Menus
while choice != "Q":
print("1: Option 1")
print("2: Option 2")
print("Q: Quit")
choice = input("Select an option: ")
# Process the choice
while server_up:
# Check server status
if not check_server_system_status():
server_up = False
send_alert("Server system error")
while data_stream.has_more_data():
data = data_stream.read_data()
process_data(data)
Learn More About the While Loop in Python
While loops and for loops are similar but also different in a few important ways.
A for loop works well when you know in advance how many times you need to iterate. For example, that's the case when looping over elements in a collection, like a list or a range in Python. You almost always know how many items are in the collection, so you also know how often to iterate.
A while loop, on the other hand, works well when the number of iterations can change. An example might be monitoring the temperature of a system and triggering an alarm if it exceeds a threshold. This flexibility makes while loops ideal for tasks where you don't know upfront how many times you'll need to repeat the code.
In an infinite loop, the condition of the while loop always evaluates to True
and never becomes False
. Infinite loops are usually unintended (i.e., a bug) because they can cause an application to crash or stop responding.
Here's an example of an unintended infinite while loop in Python:
while counter < 10:
print("Counting...")
# Intended to increment 'counter' but mistakenly resets it to 1
counter = 1
In this example, counter
mistakenly resets to 1
instead of incrementing by 1
. Therefore, the condition for the while loop always evaluates to True
, making the loop infinite. Unless the application crashes or the user stops it at some point, the loop will keep printing the message to the console forever.
To prevent an infinite loop, it's important that you provide a clear and reachable exit condition in your while loop.
A break statement provides a way to exit a loop, regardless of the original condition of the loop. This might be useful in scenarios where you want to end the loop based on a certain condition or event.
For example, consider a while loop for processing user input. Using break
, you can end an otherwise infinite loop if the user enters a special command to quit.
user_input = input("Enter a message or type 'quit' to quit: ")
if user_input == 'quit':
break # Exit the loop
Continue Statements in While Loops
A continue statement provides a way to skip an iteration without exiting the loop. Instead of exiting the loop, a continue statement proceeds to the next iteration of the loop. This might be useful when you want to bypass certain conditions within a loop.
For example, consider a while loop processing a data stream. Using continue
, you can skip incomplete or irrelevant entries and focus on relevant entries instead.
while data_stream.has_more_data():
data = data_stream.read_data()
if data is None: # Check if the data entry is incomplete print("Incomplete data received, skipping...")
continue
else:
process_data(data)
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.