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 , the loop repeats and eventually prints numbers from 1 to 5, inclusive.
