Python:如何获取IF语句以从用户输入中识别关键字?

时间:2018-10-15 08:09:08

标签: python python-3.x if-statement

几周前才开始编码,所以请原谅我的无知。

我想这样做,以便我的IF语句可以从用户输入中识别出一个关键字,而不必完全匹配。

因此,用户不必键入确切的“ Light”,而是可以键入“ Go to the light”之类的内容,并且IF语句仍将“ Light”识别为关键字并继续执行该IF或ELIF语句。

def start_room():
    if not power:
        print("You are in pitch darkness, the only thing you can see is a faint green glow from beneath the silhouette of a door to your left.")
        print("What will you do?")
        choice = input("> ")

        if choice == "Light":
            print("yadayadayada")

3 个答案:

答案 0 :(得分:1)

以下将起作用

def start_room():
    if not power:
        print("You are in pitch darkness, the only thing you can see is a faint green glow from beneath the silhouette of a door to your left.")
        print("What will you do?")
        choice = input("> ")

    if any([True for i in ['light', 'left'] if i in choice.lower()]):
        print("yadayadayada")

答案 1 :(得分:1)

您可以尝试这样做:

if "Light" in choice:
    print("yadayadayada")

答案 2 :(得分:0)

您要使用in关键字。尝试if "light" in choice: