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

如何在Python中实现菜单选择的循环验证(含整数及范围校验)

问题分析与修复

你的问题出在这几个地方:

  1. 直接转int不做异常处理:当用户输入字母/非数字时,int(input(...))会直接抛出ValueError,因为没法把非数字字符串转成整数
  2. 循环逻辑混乱:你在循环里重复调用menu()和input(),而且在option为6的分支里,没有把输入转成int,后续会触发类型错误
  3. 范围验证缺失:没有判断输入的整数是否在1-6之间,且else分支里的option.isdigit()完全无效——因为option已经是int类型,调用字符串方法会直接报错

下面是修复后的完整代码,逻辑已经理顺:

def menu():
    print('=============================')
    print('= Inventory Management Menu =')
    print('=============================')
    print('(1) Add New Item to Inventory')
    print('(2) Remove Item from Inventory')
    print('(3) Update Inventory')
    print('(4) Display Inventory')
    print('(5) Search for Item')
    print('(6) Quit')

# 模拟你未给出的函数,实际替换成你的实现
def addInventory():
    print("执行添加物品操作")
def removeInventory():
    print("执行移除物品操作")
def updateInventory():
    print("执行更新库存操作")
def printInventory():
    print("执行显示库存操作")
def searchItem():
    print("执行搜索物品操作")

# 主循环逻辑
while True:
    menu()
    # 内层循环专门处理输入验证,直到拿到有效选项
    while True:
        user_input = input("Enter your option: ")
        # 先检查输入是否为纯数字
        if not user_input.isdigit():
            print("请输入有效的整数选项(1-6)")
            continue
        # 转成整数后检查范围
        option = int(user_input)
        if 1 <= option <=6:
            break
        else:
            print("选项不在范围内,请输入1-6之间的整数")
    
    # 处理选中的菜单选项
    if option == 1:
        addInventory()
    elif option == 2:
        removeInventory()
    elif option == 3:
        updateInventory()
    elif option == 4:
        printInventory()
    elif option == 5:
        searchItem()
    elif option == 6:
        answer = input("Are you sure you want to quit? Y/N: ")
        if answer.upper() == 'Y':
            print("退出程序")
            break
        # 不退出则回到外层循环,重新显示菜单

关键修复点说明:

  • 输入验证循环:用内层循环单独处理输入,直到用户输入符合要求,避免重复代码
  • 先验数字再转类型:用user_input.isdigit()先判断输入是否为纯数字字符串,再转int,彻底避免ValueError
  • 范围检查:转成int后直接判断是否在1-6区间,不符合就提示用户重新输入
  • 简化主循环:外层用while True,只有用户选择6且确认退出时才break,逻辑更清晰
  • 退出分支优化:用answer.upper()把输入转成大写,用户输入y/Y都能识别,更友好

注意:你原代码里调用了menu()但没定义这个函数,我帮你补上了,实际使用时要确保所有自定义函数都已正确实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:36:28