Reply to user text using Python

You can create an interactive text-based response system using Python's if-elif-else statements and while loops. This approach ensures the program continues asking for input until the user provides a valid option.

The key is to use int() to convert user input to an integer and validate it against the available options.

Example

Here's a complete interactive response system ?

print("Come-on in. Need help with any bags?")

while True:
    # Loop continues until valid option is selected
    try:
        bag = int(input("(1)Yes (2)No Thanks (3)I'll get 'em later\nTYPE THE NUMBER OF YOUR RESPONSE: "))
        
        if bag == 1:
            print("You have chosen YES. We'll help with bags")
            break  # Exit loop as option is valid
        elif bag == 2:
            print("Ok you don't want any help.")
            break
        elif bag == 3:
            print("Tell us, when you want the help")
            break
        else:
            print("Invalid Choice, Please select number from 1 to 3")
    except ValueError:
        print("Please enter a valid number (1, 2, or 3)")

How It Works

The program uses several key components ?

  • while True loop: Continues execution until a valid option is selected
  • int() conversion: Converts string input to integer for comparison
  • if-elif-else chain: Handles different user responses
  • break statement: Exits the loop when valid input is received
  • try-except: Handles non-numeric input gracefully

Enhanced Version with Functions

For better code organization, you can create a reusable function ?

def get_user_response(prompt, options):
    """Get valid user response from given options"""
    print(prompt)
    
    while True:
        try:
            choice = int(input("TYPE THE NUMBER OF YOUR RESPONSE: "))
            if choice in options:
                return choice
            else:
                print(f"Invalid Choice, Please select from {list(options.keys())}")
        except ValueError:
            print("Please enter a valid number")

# Define options
bag_options = {
    1: "You have chosen YES. We'll help with bags",
    2: "Ok you don't want any help.",
    3: "Tell us, when you want the help"
}

# Use the function
prompt = "Come-on in. Need help with any bags?\n(1)Yes (2)No Thanks (3)I'll get 'em later"
user_choice = get_user_response(prompt, bag_options)
print(bag_options[user_choice])

Conclusion

Use while loops with if-elif-else statements to create interactive response systems. Always include input validation and use break to exit loops when valid input is received.

Updated on: 2026-03-24T20:47:40+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements