Back to course

Creating Interactive `while` Loops and Sentinel Values

Python Programming: The 0 to Hero Bootcamp

Interactive while Loops

while loops are excellent for scenarios where you don't know how many times the loop needs to run (e.g., waiting for user input or checking network status).

Sentinel Value

A sentinel value is a specific input or condition that signals the termination of the loop.

Example: Simple Calculator Menu

python running = True

while running: user_input = input("Enter a number to square or 'quit' to exit: ").lower()

if user_input == 'quit':
    running = False # Sentinel condition met
    print("Exiting calculator.")
    
elif user_input.isdigit():
    num = int(user_input)
    print(f"The square of {num} is {num ** 2}")
    
else:
    print("Invalid input. Try again.")

Infinite Loops

A loop where the condition never becomes False is an infinite loop. This usually freezes your program.

python

DANGER: Infinite loop example

while True:

print("Help! I'm trapped!")

Always ensure that inside your while loop, something changes that affects the control condition.