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.