You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现选择输入循环:解决咖啡馆堂食/外带输入验证问题

Fixing Your Cafe Program's Loop Issues

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 except line 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, the try block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 18:50:29