- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- datetime module
- Dictionaries
- enum
- enumerate() function
- Equality operator
- False
- Floats
- For loops
- Formatted strings
- Functions
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Less than operator
- Less than or equal to operator
- List append() method
- List insert() method
- List pop() method
- List sort() method
- Lists
- map() function
- Match statement
- Modules
- None
- not operator
- or operator
- Parameters
- print() function
- range() function
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
PYTHON
Python While Loops: Syntax, Usage, and Examples
The Python while loop is a control flow statement that runs a block of code for as long as a specified condition is true. The while loop will execute the code in the body of the loop until the specified condition becomes false.
How to Use the While Loop in Python
The syntax of a while loop in the Python programming language is straightforward. Here's the basic structure:
while condition:
# 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 toFalse
, 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
Similar to the for loop, the Python while loop allows you to repeat code without having to type out the repetitions. But while loops are particularly great when the number of iterations is unknown at the time the loop starts. While loops are also well-suited for tasks that require continuous checking and execution until a particular condition changes.
Examples of While Loops in Python
While loops are very common in many Python applications. Here are some simple examples:
User Input Validation
The while loop is perfect for prompting users for input until they provide a valid response. For example, a program might repeatedly ask for a username until the input matches certain criteria. In this case, the username needs to be longer than four characters.
username = None
while not username:
username_input = input("Enter a valid username: ")
if len(username_input) > 4:
username = username_input
Main Menus
In applications with main menus, a while loop can display the menu until users decide to exit. This makes for an intuitive and user-friendly interface.
choice = ""
while choice != "Q":
print("1: Option 1")
print("2: Option 2")
print("Q: Quit")
choice = input("Select an option: ")
# Process the choice
Monitoring Applications
Within monitoring applications, a while loop might check the system status of a server. For example, services to monitor a server's uptime and send alerts in case of problems might use a while loop.
server_up = True
while server_up:
# Check server status
if not check_server_system_status():
server_up = False
send_alert("Server system error")
Real-Time Data Streams
Working with real-time data streams, a while loop might read and process data as it arrives (and for as long as it arrives). For instance, applications reading and processing sensor data from a weather station might use a while loop.
data_stream = get_data_stream()
while data_stream.has_more_data():
data = data_stream.read_data()
process_data(data)
Learn More About the While Loop in Python
While Loop vs. For Loop
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.
Infinite Loops
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:
counter = 1
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.
Break Statements in While Loops
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.
while True: # Infinite loop
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.
data_stream = get_data_stream()
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.