如何验证某些数字的输入?

时间:2015-10-31 19:19:05

标签: python

我试图找出如何验证用户输入,以便他们的输入只能是以下数字之一:1 2或3.我当前的代码似乎没有识别变量包含3个数字:

我的代码

options = "1", "2", "3"

    while True:
        option = input("\nEnter a Number [1][2][3]: ")
        if option == options:
            print ("Great")
        else:
            print ("Sorry, Invalid Input! Please Enter either [1] [2] [3]")

此代码不起作用,因为options变量未正确写入,以及其下的代码块。任何帮助都会很棒!

2 个答案:

答案 0 :(得分:0)

使用list代替,这就是我们拥有它们的原因:

options = ["1", "2", "3"]

然后,使用检查列表中是否有值的in运算符,您可以执行成员资格测试:

while True:
    option = input("\nEnter a Number [1][2][3]: ")
    if option in options:
        print ("Great")
    else:
        print ("Sorry, Invalid Input! Please Enter either [1] [2] [3]")

答案 1 :(得分:0)

使用具有0(1)查找时间复杂度的集合

options = set('1', '2', '3')

然后在你的循环中

if option in options:
    print ("Great")
    break # added break to end the while loop after a valid input

但是如果你需要在每个位置都有一个值,你可以使用一个字典,该字典的查找时间复杂度为0(1),但在存储/内存方面更加强大

options = {
    '1': 'some value here',
    '2': 'some value here',
    '3': 'some value here'
}
相关问题