检查输入是否在python中的数字列表中

时间:2015-12-24 04:27:31

标签: python list python-3.x python-3.5

numbers = [1,2,3,4,5,6,7]
x = input()
if x in numbers:
    print("Hey you did it")
else:
    print("Nope")

我不确定我在这里做错了什么,但它总是告诉我我的号码不在列表中......即使它是。但是,使用字符串可以正常工作。

帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:5)

输入是一个字符串,因此您将字符串与整数进行比较。首先转换为int然后进行成员资格测试:

numbers = [1,2,3,4,5,6,7]
x = input()
if int(x) in numbers:
    print("Hey you did it")
else:
    print("Nope")

为了使这一点更加健壮,你应该处理如果用户没有输入整数将会出现的ValueError(总会有一个用户输入'cheeseburger'而不是数字):

numbers = [1,2,3,4,5,6,7]
x = input()
try:
    i = int(x)
    if i in numbers:
        print("Hey you did it")
    else:
        print("Nope")
except ValueError:
    print("You did not enter a number")