如何在python中使用if语句检查List的内容

时间:2017-02-05 18:25:05

标签: python list if-statement

我是python的新手,我编写了以下代码但是如果输入B则不会降低分数,如果输入How,Hi等,它会将分数增加1但不输入8并且不会减少如果输入B则得分。任何人都可以提供帮助。

grid = [8,“B”,“How”,“嗨”,“嘿”,“你好吗”,“怎么样”,“怎么样”,“你好”]

def Play():   
    count=0      
    score=0    
    while (count<11):
        I=input("Enter your guess")
        if I in grid:
           score+=1
           print("Your score is:", score)
        elif I in grid == "B":
           score=0
           print("Your score is:",score)
        else:
           print("I don't understand")
        count+=1

1 个答案:

答案 0 :(得分:1)

input()将输入存储为字符串。因此,如果用户输入8,则会将其存储为"8""8"8不同,因此if I in grid将评估为False。要解决此问题,您可以在列表中将8更改为"8",或添加elif I == "8":

elif I in grid == "B":永远不会评估为真。这是因为您正在检查(I in grid) == ("B")I in grid始终为TrueFalse,因此您要将"B"与布尔值进行比较,该布尔值始终为False

更简单的方法是在`grid:

中将8更改为"8"
grid=["8","B","How", "Hi", "Hey", "How are you doing", "How's it going", "How", "Hello"]

并检查第一个I == "B"语句中是否if

if I in grid:
    if I == "B":
        score=0
    else:
        score+=1
    print("Your score is:",score)
else:
    print("I don't understand")