A Boolean flag is a single Boolean variable used to indicate whether a specific condition has been met, often controlling the flow of loops and conditional statements in a program.
Example
while not valid_entries:
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
valid_entries = True # Set flag to True if inputs are valid
except ValueError:
print("Invalid input. Please enter numeric values.")
sum_result = num1 + num2
print(f"The sum of {num1} and {num2} is {sum_result}.")
Explanation
- Boolean Flag:
valid_entries
is used to control the while loop. - While Loop: Continues to prompt for input until valid numeric values are entered.
- Try-Except Block: Catches invalid inputs and prompts the user to re-enter.
- Addition: Once valid entries are obtained, the sum is calculated and displayed.