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

2024-10-03 15:32:07 发布

您现在位置:Python中文网/ 问答频道 /正文

几周前刚开始编写代码,请原谅我的无知。你知道吗

我想这样做,我的IF语句将识别一个关键字从用户输入,而不是它必须是一个完全匹配。你知道吗

因此,用户不必精确地键入“Light”,他们可以键入类似“gotothelight”的内容,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")

Tags: the代码用户you内容键入if关键字
3条回答

以下步骤将起作用

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")

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

你可以这样做:

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

相关问题 更多 >