Blog Post #31: Repeating Yourself: An Introduction to the while Loop

In Part 2 so far, we’ve focused on conditional logic—using if, elif, and else to make our programs choose a path. This is one of the two main types of “control flow.” The other, equally important type is repetition.

What if you wanted your program to perform the same action multiple times? You could copy and paste the same lines of code, but this is inefficient, messy, and hard to manage if you need to make a change. To solve this, programming languages have a concept called loops.

In this post, we’ll learn about our first type of loop in Python: the while loop, which allows us to repeat a block of code as long as a certain condition remains true.

The Logic of the while Loop

A while loop is a control flow structure that repeatedly executes an indented block of code as long as a given boolean expression evaluates to True.

The logic is very intuitive and reads like an English sentence: “While this condition is true, do this block of code.”

Think of it like telling someone, “While the music is playing, keep dancing.” Before each dance move, they will check the condition (“is the music still playing?”). If the answer is yes, they will perform the action (dance). This check-and-act cycle continues until the music stops.

Anatomy of a while Loop

The syntax for a while loop is very similar to the if statement we’re already familiar with.

while condition:
    # Loop body: one or more lines of indented code
    # that will be repeated as long as the 
    # condition is True.

To build a successful while loop that eventually stops, you typically need three parts:

  1. Initialization: A variable that is set up before the loop begins. This is often called a counter.
  2. Condition: The test in the while statement that checks the variable before each repetition. The loop continues as long as this condition is True.
  3. Update: A line of code inside the loop that modifies the variable from the initialization step. This is crucial to ensure the condition will eventually become False, allowing the loop to end.

A while Loop in Action: A Simple Counter

The best way to understand a while loop is to build one. Let’s write a program that prints a message five times.

# 1. Initialization
counter = 1

# 2. Condition
while counter <= 5:
    # Code to be executed in the loop body
    print(f"This is repetition number: {counter}")
    
    # 3. Update
    counter += 1 # Increment the counter by 1

print("The loop has finished!")

Let’s trace the execution of this script step-by-step:

  1. Python initializes counter to 1.
  2. It checks the condition: Is 1 <= 5? Yes, it’s True.
  3. It executes the loop body: it prints “This is repetition number: 1” and then updates counter to 2.
  4. The loop body is finished, so Python goes back to the top and checks the condition again.
  5. Is 2 <= 5? Yes. It prints the message and updates counter to 3.
  6. This continues until counter is 5. The condition 5 <= 5 is still True, so it prints the message and updates counter to 6.
  7. It checks the condition again: Is 6 <= 5? No, this is False.
  8. Because the condition is now False, the loop terminates. Python skips the loop body and continues execution on the first line after the loop, printing “The loop has finished!”.

The counter += 1 line is the most critical part here. It’s the “update” step that ensures the loop makes progress towards its end.

What’s Next?

You’ve now learned how to create a while loop to repeat actions in your code. By setting up an initial condition and ensuring it gets updated within the loop, you can control exactly how many times a block of code is executed.

In our example, we were very careful to include counter += 1 to ensure our loop eventually ended. But what happens if you forget this step or create a condition that can never be false? This leads to a common and sometimes frustrating problem. In Post #32, we will explore the danger of “infinite loops” and learn how to identify and avoid them.

Author

Debjeet Bhowmik

Experienced Cloud & DevOps Engineer with hands-on experience in AWS, GCP, Terraform, Ansible, ELK, Docker, Git, GitLab, Python, PowerShell, Shell, and theoretical knowledge on Azure, Kubernetes & Jenkins. In my free time, I write blogs on ckdbtech.com

Leave a Comment