python - 如何在Python中循环菜单选择验证?

标签 python loops validation menu

我试图创建一个循环来验证我的菜单选项是否为整数,但在输入字母 line 138, in <module> option = int(input("Enter your option:")) ValueError: invalid literal for int() with base 10: 'test' 时收到此错误。抱歉,如果代码很困惑,我只用了大约 2 周的 python 时间,所以仍在学习。 理想情况下,我希望验证也将选择范围限制在 1-6 个范围内。 附:我知道这是错的,但我就是不知道错在哪里。 这是我的代码:

    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')

#Selecting menu option
menu()
option = int(input("Enter your option:"))
while option !=0:
    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 == 'Y':
            exit()
        else:
            menu()
            option = (input("Enter your option:"))
    else:
        if option.isdigit():
            pass
        else:
            print("Enter a valid option: ")
    menu()
    option = int(input("Enter your option:"))

最佳答案

试试这个:

option = input("Enter your option:")

while not option.isdigit():
   option = input("Enter a valid option:")

option = int(option)

您还可以检查数字是否在特定范围内:

option = input("Enter your option:")

while not option.isdigit() or int(option) < 1 or int(option) > 6:
    option = input("Enter a valid option:")

option = int(option)

关于python - 如何在Python中循环菜单选择验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73393335/

相关文章:

sql-server - 我如何批量读取用户名列表并在 sql 语句中使用这些用户名?

java - 对象验证和赋值的问题

laravel - 如何在 Laravel 中让按钮对管理员类型用户可见一次?

Python - 将txt文件读入列表 - 显示新列表的内容

python - 将工作目录设置为笔记本目录

javascript - 使用自动索引在循环中创建多维数组

java - 使用循环用 5 个给定字符串填充数组

没有为 aws sam cli 配置 Python

python - Numpy - 引用单个元素时保留指针

c# - 如何使用此枚举列表减少代码