Let's buckle up for our journey into the fascinating world of While Loops. Visualize piloting a spaceship on an uncharted route, making a pit stop at every interesting planet until you find the one that harbors intelligent life. This adventure encapsulates what While Loops do: they continue running tasks until a specific condition changes. In this lesson, we aim to master the usage of While Loops, understand the concept of 'indefinite iteration', and control the loop's execution effectively.
A while loop allows the code to execute repeatedly based on a specific condition. If the condition remains True, it continues to run, similar to an if statement. Let's look at a while loop that counts from 1 to 5:
The output of the code is:
Here's the basic structure of a while loop:
In our example, count <= 5 is the condition, and print(count); count += 1 is the code to be executed. As long as the condition count <= 5 holds True, the loop repeats and eventually prints numbers from 1 to 5, inclusive.
Let's delve into the intricacies of While Loops:
- Firstly, Python checks if the
whileloop's condition isTrue. - If the condition is
True, it executes the loop's code. - Then, it cycles back to the first step.
This continues until the condition becomes False.
While writing a while loop, make sure the loop's condition eventually turns False to avoid infinite loops. An infinite loop could potentially crash your system. Here's an example:
To prevent such a catastrophe, we often use the break statement. The break statement provides an escape hatch, immediately terminating the loop it's in. We will cover the break operator more extensively later in this course.
