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

Python菜单选择程序错误输入后无法识别有效输入问题求助

问题根因定位
  • 核心逻辑缺陷1:无外层循环控制菜单重复选择,所有输入校验和菜单匹配逻辑仅会执行一次,单次流程走完后程序就会直接终止
  • 核心逻辑缺陷2:仅首次输入为数字时才会走菜单匹配分支,两个异常分支(首次输入非数字、首次输入数字但超出1-4范围)中获取到的新输入值,都没有后续的类型转换和菜单匹配逻辑,直接就结束了程序运行
  • 核心逻辑缺陷3:非数字输入仅做了一次重试,没有做持续校验,若第二次依然输入非数字也会直接失效
修复后完整代码
def menu():
    print("1. Create new User")
    print("2. View User")
    print("3. Update User")
    print("4. Quit ") 

# 外层循环控制菜单持续运行
while True:
    menu()
    selection = input("Select a menu- Input a number:")
    # 统一校验输入是否为数字
    if not selection.isdigit():
        print("You have input a non digit value. Select again:")
        continue
    selection = int(selection)
    # 匹配菜单选项
    if selection == 1:
        print("::menu 1::")
        newName = input("Input first name : ")
        newSurname = input("Input last name : ")
    elif selection == 2:
        print("::menu 2::")
    elif selection == 3:
        print("::menu 3::")
    elif selection == 4:
        print("you have logged out")
        # 主动退出循环结束程序
        break
    else:
        print(f"There is no menu {selection}")
        print()
修复说明
  • 新增外层while True循环控制菜单流程持续运行,直到用户选择4时主动退出
  • 把输入校验、类型转换、菜单匹配逻辑全部放到循环内,所有重试场景都会重新走完整的校验匹配流程
  • 去掉冗余的重复输入代码,用continue直接触发下一轮循环完成重试,避免逻辑遗漏

内容的提问来源于stack exchange,提问作者user17490056

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:36:09