首页 > 解决方案 > 验证输入选择和循环,直到获得 4 个选项之一

问题描述

我在这里尝试了很多变化都无济于事。我有一个包含 4 个选项的菜单,如果在打印出响应并重新提示仅选择 1、> 2、3 或 4 时未选择选项 1、2、3 或 4,我正在尝试循环。我试过了:

print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = int(input("What would you like to choose [1,2,3,4]? "))
while choice not in ['1','2','3','4']:
    print: ("Please enter 1, 2, 3 or 4. ")
    choice = int(input("What would you like to choose [1,2,3,4]? "))

print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = input("What would you like to choose [1,2,3,4]? ")
while choice not '1' and choice not '2' and choice not '3' and choice not '4':
    print: ("Please enter 1, 2, 3 or 4. ")
    selection = input("What would you like to choose [1,2,3,4]? ")

print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = int(input("What would you like to choose [1,2,3,4]? "
    while choice != '1' and user_input != '2' and user_input != '3' and choice != 4:
    choice = int(input("Please enter 1, 2, 3 or 4. "))

我得到了从语法错误到不正确输出的范围或错误(不会打印“请输入 1、2、3 或 4。”并且不会循环。只有在非常简单的事情之后,不想使用退出语句- 请问我哪里错了?

标签: pythonloopsvalidationinput

解决方案


您正在请求一个整数并且您正在寻找它作为char,将您的验证列表更改为整数并且您的第一个选项有效:

print("Options:")
print("Option 1")
print("Option 2")
print("Option 3")
print("Option 4")
choice = int(input("What would you like to choose [1,2,3,4]? "))
while choice not in [1,2,3,4]:
    #print: ("Please enter 1, 2, 3 or 4. ")
    print("Please enter 1, 2, 3 or 4. ")
    choice = int(input("What would you like to choose [1,2,3,4]? "))

这部作品


推荐阅读