使用循环检查变量是否在字典中

时间:2013-10-16 06:28:10

标签: python dictionary

所以对于上课,我正在制作一个糟糕的文字冒险游戏。我想检查用户输入的可接受单词词典。但是,当我这样做时,我得到一个'TypeError:'set'对象不可订阅'。我该如何解决这个问题?

“游戏”的小部分代码:

def butts():
    southLib={"long thing", "rough thing", "cylinder thing", "floor thing", "home"}

    userPoop = str(input("Would you like to poop in the long thing, rough thing, cylinder thing, floor thing, or home? None?"))

    while southLib[userPoop] == None:
        print("I do not understand")
        userPoop = str(input("Would you like to poop in the long thing, rough thing, cylinder thing, floor thing, or home? None?"))

butts()

2 个答案:

答案 0 :(得分:0)

进行适当的收容检查。

while userPoop not in southLib:

答案 1 :(得分:0)

如果您想检查某些内容是否存在,请使用not in运算符:

>>> my_set = {"foo", "bar", "baz"}
>>> "foo" not in my_set
False
>>> "qux" not in my_set
True

(同样,您可以使用in检查某个 中是否有