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

Implementing User Input Driven Loops

Learners will be able to create interactive programs that continue processing or gathering user input until a specific sentinel value is provided.

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

  1. Initialization: We initialize user_command as an empty string so the while loop has something to evaluate immediately.
  2. The Condition: The loop checks if user_command != "quit". If it is true, the loop block runs.
  3. 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!
  4. Logic: We use if/elif statements 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 final print statement.

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.