Python实现选择输入循环:解决咖啡馆堂食/外带输入验证问题
Hey Erin, let's work through fixing your code together! The main reason your code won't run is an incomplete except statement—Python requires that you either specify an exception type to catch (like except ValueError:) or at least add a colon if you want a broad catch-all (though that's not needed here).
Wait, actually, looking closer at your logic: since you're checking if the input matches the strings "1" or "2", you don't even need the try/except block at all! Those blocks are meant for handling code that might throw an error (like converting input to an integer), but string comparisons here won't trigger exceptions.
Let's break down your original errors:
- The
exceptline is missing both an exception type and a colon (:)—this is a syntax error that stops your code from running entirely. - Even if you fixed the
except, thetryblock doesn't contain any code that would actually throw an exception in this scenario, making it redundant. - You also weren't exiting the loop after valid input—so even if someone entered 1 or 2, the program would keep asking the question forever!
Corrected Code (String Input Version)
Here's a cleaned-up version that works as intended:
print("Will you be dining in or ordering take out?") while True: where = input("For Dine In, Type 1. For Take Out, Type 2: ") if where == "1": print("Thank you for dining in with us. Please fill out the following: ") break # Exit the loop once valid input is received elif where == "2": print("Thank you for choosing take out. Please fill out the following: ") break # Stop looping after valid selection else: print("Invalid response, please type 1 or 2: ")
Optional: Integer Input Version
If you'd prefer to work with integer inputs (so users enter numeric values instead of strings), here's how you'd properly use try/except to handle non-numeric entries:
print("Will you be dining in or ordering take out?") while True: try: where = int(input("For Dine In, Type 1. For Take Out, Type 2: ")) if where == 1: print("Thank you for dining in with us. Please fill out the following: ") break elif where == 2: print("Thank you for choosing take out. Please fill out the following: ") break else: print("Invalid response, please type 1 or 2: ") except ValueError: print("Please enter a valid number (1 or 2)!")
In this version, the try/except is useful because int() will throw a ValueError if the input can't be converted to an integer—we catch that to give the user a clear prompt.
内容的提问来源于stack exchange,提问作者Erin McKee

