How to Check If a Loop Has Completed in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to determine if a loop has completed in Python. This involves understanding how for loops execute and exploring different techniques to track loop completion.

You'll start by examining a basic for loop example, iterating through a list of fruits and printing each one. Then, you'll learn how to use a flag variable to monitor the loop's progress and finally, you'll discover how to leverage the else clause in conjunction with loops to execute code only after the loop has finished normally.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/booleans("Booleans") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/ControlFlowGroup -.-> python/break_continue("Break and Continue") python/DataStructuresGroup -.-> python/lists("Lists") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/booleans -.-> lab-559538{{"How to Check If a Loop Has Completed in Python"}} python/conditional_statements -.-> lab-559538{{"How to Check If a Loop Has Completed in Python"}} python/for_loops -.-> lab-559538{{"How to Check If a Loop Has Completed in Python"}} python/break_continue -.-> lab-559538{{"How to Check If a Loop Has Completed in Python"}} python/lists -.-> lab-559538{{"How to Check If a Loop Has Completed in Python"}} python/data_collections -.-> lab-559538{{"How to Check If a Loop Has Completed in Python"}} end

Learn How Loops Execute

In this step, you will learn how for loops execute in Python. Loops are fundamental programming constructs that allow you to repeat a block of code multiple times. Understanding how loops work is crucial for writing efficient and effective programs.

Let's start with a simple example. Create a file named loop_example.py in your ~/project directory using the VS Code editor.

## loop_example.py
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

This code iterates through a list of fruits and prints each fruit to the console.

To run this script, open your terminal in VS Code and execute the following command:

python loop_example.py

You should see the following output:

apple
banana
cherry

Let's break down what's happening in the code:

  1. fruits = ["apple", "banana", "cherry"]: This line creates a list named fruits containing three strings: "apple", "banana", and "cherry".
  2. for fruit in fruits:: This line starts a for loop. The loop iterates over each element in the fruits list. In each iteration, the current element is assigned to the variable fruit.
  3. print(fruit): This line is inside the loop. It prints the value of the fruit variable to the console.

The loop executes three times, once for each fruit in the list. In the first iteration, fruit is "apple", so "apple" is printed. In the second iteration, fruit is "banana", so "banana" is printed. In the third iteration, fruit is "cherry", so "cherry" is printed.

Now, let's modify the script to include the index of each fruit. Modify the loop_example.py file as follows:

## loop_example.py
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

In this modified code, we use the enumerate() function to get both the index and the value of each element in the list.

Run the script again:

python loop_example.py

You should see the following output:

Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry

The enumerate() function returns a sequence of (index, element) pairs. In each iteration, the index is assigned to the variable index, and the element is assigned to the variable fruit.

Understanding how loops execute is essential for writing programs that can process collections of data. In the next steps, you will learn more advanced techniques for controlling the execution of loops.

Set a Flag Variable to Track Completion

In this step, you will learn how to use a flag variable to track the completion of a task within a loop. A flag variable is a boolean variable (either True or False) that indicates whether a certain condition has been met. This is a common technique for controlling the flow of a program.

Let's consider a scenario where you want to search for a specific number in a list and stop the loop as soon as you find it. Create a file named flag_example.py in your ~/project directory using the VS Code editor.

## flag_example.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 5
found = False  ## Initialize the flag variable

for number in numbers:
    print(f"Checking number: {number}")
    if number == target:
        found = True
        print(f"Found the target: {target}")
        break  ## Exit the loop

if found:
    print("Target found in the list.")
else:
    print("Target not found in the list.")

In this code, we initialize a flag variable named found to False. The loop iterates through the numbers list. If the current number is equal to the target, we set found to True, print a message, and exit the loop using the break statement. After the loop, we check the value of found. If it's True, we print a message indicating that the target was found. Otherwise, we print a message indicating that the target was not found.

To run this script, open your terminal in VS Code and execute the following command:

python flag_example.py

You should see the following output:

Checking number: 1
Checking number: 2
Checking number: 3
Checking number: 4
Checking number: 5
Found the target: 5
Target found in the list.

Notice that the loop stops as soon as the target number (5) is found. The break statement exits the loop, preventing further iterations.

Now, let's modify the script to search for a number that is not in the list. Change the target variable to 15:

## flag_example.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 15
found = False  ## Initialize the flag variable

for number in numbers:
    print(f"Checking number: {number}")
    if number == target:
        found = True
        print(f"Found the target: {target}")
        break  ## Exit the loop

if found:
    print("Target found in the list.")
else:
    print("Target not found in the list.")

Run the script again:

python flag_example.py

You should see the following output:

Checking number: 1
Checking number: 2
Checking number: 3
Checking number: 4
Checking number: 5
Checking number: 6
Checking number: 7
Checking number: 8
Checking number: 9
Checking number: 10
Target not found in the list.

In this case, the loop iterates through the entire list without finding the target number. The found variable remains False, and the "Target not found in the list." message is printed.

Using a flag variable is a simple and effective way to track the completion of a task within a loop. This technique is useful in many different scenarios, such as searching for an element in a list, validating user input, or processing data from a file.

Use the else Clause with Loops

In this step, you will learn how to use the else clause with for loops in Python. The else clause in a for loop is executed when the loop completes normally, i.e., when the loop is not terminated by a break statement. This can be useful for performing actions that should only be done if the loop completes without finding a specific element or encountering an error.

Let's revisit the example from the previous step, where we searched for a target number in a list. We can use the else clause to print a message if the target number is not found. Create a file named else_example.py in your ~/project directory using the VS Code editor.

## else_example.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 15

for number in numbers:
    print(f"Checking number: {number}")
    if number == target:
        print(f"Found the target: {target}")
        break
else:
    print("Target not found in the list.")

In this code, the else clause is associated with the for loop. If the loop completes without finding the target (i.e., the break statement is not executed), the code inside the else clause is executed.

To run this script, open your terminal in VS Code and execute the following command:

python else_example.py

You should see the following output:

Checking number: 1
Checking number: 2
Checking number: 3
Checking number: 4
Checking number: 5
Checking number: 6
Checking number: 7
Checking number: 8
Checking number: 9
Checking number: 10
Target not found in the list.

Since the target (15) is not in the numbers list, the loop completes normally, and the else clause is executed, printing the "Target not found in the list." message.

Now, let's modify the script to include the target number in the list. Change the target variable to 5:

## else_example.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 5

for number in numbers:
    print(f"Checking number: {number}")
    if number == target:
        print(f"Found the target: {target}")
        break
else:
    print("Target not found in the list.")

Run the script again:

python else_example.py

You should see the following output:

Checking number: 1
Checking number: 2
Checking number: 3
Checking number: 4
Checking number: 5
Found the target: 5

In this case, the loop is terminated by the break statement when the target (5) is found. Therefore, the else clause is not executed.

The else clause in a for loop provides a concise way to execute code when the loop completes normally, without being interrupted by a break statement. This can be useful for handling cases where you need to perform a specific action only if a certain condition is not met during the loop's execution.

Summary

In this lab, you learned how for loops execute in Python by iterating through a list of fruits and printing each fruit along with its index. The lab demonstrated the basic structure of a for loop, including the use of the enumerate() function to access both the index and value of each element in the list during iteration.

The initial example iterated through a list of fruits and printed each fruit. The subsequent modification used enumerate() to print both the index and the fruit, illustrating how to access both the position and value of elements within a loop.