
The 'While' Loop: Repeating Based on a Condition
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!")