Course contentsShow
← Python
Lesson 128 of 1,0602. Control Flow and LogicFree lesson

Using Flag Variables for State Tracking

Learners will utilize Boolean flag variables to signal and capture specific logical states encountered during complex iterative processes for later decision-making.

In this lesson, you will learn how to use Boolean "flag" variables to "remember" if a specific event occurred while your code was running.

Why do we need Flags?

Sometimes, your program performs a long sequence of operations (like looping through a list), and you need to know later if a specific condition was ever met. A flag is just a simple variable—usually starting as False—that acts like a light switch. You flip it to True the moment you encounter the data you are looking for.

The Logic Pattern

Imagine you are checking a list of user logins to see if anyone logged in from an "untrusted" country. Instead of stopping the program immediately, you might want to finish checking the whole list first, but "mark" the account as compromised to handle it later.

Here is how you implement that state tracking:

is_compromised = False  # The flag starts at False

logins = ["USA", "USA", "Canada", "Unknown", "USA"]

for country in logins:
    if country == "Unknown":
        is_compromised = True  # We flip the switch!

# Later, we use the flag to make a decision
if is_compromised:
    print("Security alert: An unauthorized login was detected.")
else:
    print("All logins verified.")

How it works

  1. Initialize: You define the flag outside of the loop so it persists throughout the entire process.
  2. Observe: Inside your loop, you check for your condition.
  3. Signal: If the condition is met, you update the flag to True. Once it is True, it usually stays True for the rest of the execution.
  4. Act: After the loop finishes, you check the value of the flag to determine what the program should do next.

By using this approach, your code "remembers" what happened during the iteration, allowing you to separate the act of finding information from the act of acting on that information.

Key Takeaway: A flag variable acts as a memory aid, allowing your program to record that a specific event occurred during a loop so that it can make an informed decision once the loop concludes.