Mastering User Input Driven Loops
In this lesson, you will learn how to create interactive programs that stay active by waiting for user input, only stopping when the user decides to "quit."
The Concept of a Sentinel Value
Up until now, you have used loops to iterate a specific number of times or through a fixed collection of items. However, many programs need to run indefinitely until a user provides a specific signal. We call this signal a sentinel value.
A sentinel value is a specific piece of data—like the string "quit" or the number -1—that tells your program, "I am finished; please stop the loop."
Putting It Into Practice
To implement this, you combine a while loop with an input() function. You compare the user's input to your sentinel value inside the loop condition.
Here is how you might build a simple interactive command center:
user_command = ""
# The loop continues as long as the user hasn't typed "quit"
while user_command != "quit":
user_command = input("Enter a command (or type 'quit' to exit): ")
if user_command == "hello":
print("Hi there!")
elif user_command == "help":
print("I am a command loop. Type 'quit' to stop.")
elif user_command != "quit":
print("I don't recognize that command.")
print("Goodbye!")
How It Works
- Initialization: We initialize
user_commandas an empty string so thewhileloop has something to evaluate immediately. - The Condition: The loop checks if
user_command != "quit". If it is true, the loop block runs. - Updating the Variable: Inside the loop, we use
input()to update the variable. This is crucial—if we didn't update it, the loop would run forever! - Logic: We use
if/elifstatements to handle specific commands, ensuring we only react to known inputs. Once the user types"quit", the condition becomes false, and the loop terminates, moving to the finalprintstatement.
By using this pattern, you move from writing static scripts to building flexible, interactive tools that respond directly to user intent.
Key Takeaway: Use a while loop combined with a sentinel value to keep a program running until the user explicitly signals to stop.