检查列表中的一个元素是否等于特定数字?

时间:2013-11-26 22:03:28

标签: python python-3.x

例如

hidden_list = [63,45,76,8,59,04,13]

user_input = int(input("guess one number in the hidden list"))

如何判断用户是否使用if语句正确猜到了列表中的一个数字?

2 个答案:

答案 0 :(得分:2)

if user_input in hidden_list:
    # tell them they won

答案 1 :(得分:2)

使用in

hidden_list = [63,45,76,8,59,04,13]

user_input = int(input("guess one number in the hidden list"))

if user_input in hidden_list:
    print "You won!"
else:
    print "You lost."

in测试集合中的成员资格。换句话说,上面的代码正在测试user_inputhidden_list的成员。

参见下面的演示:

>>> hidden_list = [63,45,76,8,59,04,13]
>>> user_input = int(input("guess one number in the hidden list "))
guess one number in the hidden list 63
>>> if user_input in hidden_list:
...     print "You won!"
... else:
...     print "You lost."
...
You won!
>>> user_input = int(input("guess one number in the hidden list "))
guess one number in the hidden list 100
>>> if user_input in hidden_list:
...     print "You won!"
... else:
...     print "You lost."
...
You lost.
>>>