Topic Overview and Actualization

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.

While Loop Discovery

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:

count = 1
while count <= 5:
    print(count) # Will print numbers from 1 to 5, inclusive
    count += 1

The output of the code is:

1
2
3
4
5

Here's the basic structure of a while loop:

while condition:
    # code to be executed

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.

Journey through the While Loop Galaxy

Let's delve into the intricacies of While Loops:

  1. Firstly, Python checks if the while loop's condition is True.
  2. If the condition is True, it executes the loop's code.
  3. Then, it cycles back to the first step.

This continues until the condition becomes False.

Steering the While Loop Spaceship - Control Flow

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:

# INFINITE LOOP EXAMPLE - DO NOT RUN!
count = 1
while count <= 5: 
    print(count) # Always prints 1
    # Forgetting to increment count results in an infinite loop.

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.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal