So far, we've explored if and elif statements, which allow your programs to make decisions based on whether a condition is true or false. But what if you need to repeat an action not a fixed number of times, but as long as a certain condition remains true? That's where the while loop comes in!
The while loop is a powerful control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to True. Think of it as a 'loop until' mechanism. Once the condition becomes False, the loop terminates, and the program continues with the code following the loop.
Here's the basic syntax of a while loop:
while condition:
# Code to be executed repeatedly
# as long as the condition is True
pass # Placeholder, replace with your codeLet's break this down:
whilekeyword: This signals the start of awhileloop.condition: This is an expression that Python evaluates. If it'sTrue, the code block inside the loop will run. If it'sFalse, the loop will stop.:colon: Marks the end of the condition and the beginning of the indented code block.- Indented code block: This is the set of statements that will be executed repeatedly. Indentation is crucial in Python to define code blocks.
It's extremely important that the code inside the while loop eventually makes the condition evaluate to False. If the condition always remains True, you'll create an infinite loop, which will cause your program to run forever, or until you manually stop it. This is usually an undesirable outcome!
Let's look at a simple example. Imagine you want to count down from 5 to 1:
count = 5
while count > 0:
print(count)
count = count - 1 # Or count -= 1
print("Blast off!")In this example:
- We initialize a variable
countto5. - The
whileloop checks ifcount > 0. Initially, this isTrue. - Inside the loop, we print the current value of
count. - We then decrement
countby1. This is the crucial step that ensures the condition will eventually becomeFalse. - The loop repeats. When
countbecomes0, the conditioncount > 0will beFalse, and the loop will terminate. - Finally, "Blast off!" is printed.
graph TD
A[Start]
B{Is count > 0?}
C[Print count]
D[Decrement count]
E[Blast off!]
F[End]
A --> B
B -- Yes --> C
C --> D
D --> B
B -- No --> E
E --> F
Here's another common use case: getting user input until a valid value is provided.
user_input = ""
while user_input.lower() != "quit":
user_input = input("Enter a command (or 'quit' to exit): ")
print(f"You entered: {user_input}")
print("Exiting the program.")In this code:
- The loop continues as long as the
user_input(converted to lowercase) is NOT equal to "quit". - Inside the loop, we prompt the user for input.
- Once the user types "quit" (regardless of case), the condition
user_input.lower() != "quit"becomesFalse, and the loop ends. - The program then prints "Exiting the program."
Remember to always ensure that your while loop has a mechanism to eventually terminate. This typically involves modifying a variable that is part of the loop's condition within the loop's body. This is often referred to as the 'loop control variable'.