繁体   English   中英

Python 3.8.2 | 为什么我的输入不接受我的答案,即使它是有效的? (功能)

[英]Python 3.8.2 | Why does my input doesn't accept my answer even if it's a valid one? (function)

我是 Python 的初学者。 我想创建一个文本游戏,其中包含一些 MCQ,并保存一些代码,我创建了一个 function 询问并等待答案(input()),但它只能接受一些答案(例如 a、b、c , d...),但如果它不是一个有效的答案,它会重复这个问题(while 循环)。 它有效,但即使我回答正确,它也会重复。 你能帮我吗?

这是function,

def carsaction(*instructions):
    """
    Fonction servant à faire un choix pour interagir avec soi même.
    """
    commande = str(None)
    while commande.lower() != instructions:
        commande = str(input("Quelle action choisissez-vous?"))
        if commande.lower() == instructions:
            break
        else:
            print("Réponse non valide!")
            time.sleep(3)
            continue

当我使用它时:

carsaction("a","b")

___这是另一回事

    print("Vous vous trouvez quelque par. Que faites-vous?")
    time.sleep(1)
    print("""
        a: Explorer
        b: Regarder l'inventaire
        """)
    carsaction(["a","b"])
    if carsaction(["a"]) == "a":
        time.sleep(3)
        print("Vous voulez donc explorer.")
        time.sleep(3)
        [code after...]
    else:
        print("Test")

instructions是一个列表,所以你应该if commande.lower() in instructions

出于同样的原因,您的while中的标准永远不会是错误的(即使使用break语句,它实际上也是无用的)。 while commande.lower() not in instructions:会更好。

你可以尝试这样的事情:

def carsaction(*instructions):
    """
    Fonction servant à faire un choix pour interagir avec soi même.
    """
    commande = str(None)
    while commande.lower() not in instructions:
        commande = str(input("Quelle action choisissez-vous?"))
        if commande.lower() in instructions:
            break
        else:
            print("Réponse non valide!")
            continue

您应该将列表作为包含有效字符作为元素的参数传递,并让您的 while 循环检查用户输入是否是列表中的有效字符之一,但您的代码尝试将整个 function 参数与输入而不是匹配只有一个或多个。

为了解决这个问题,您应该创建一个列表作为参数,并在定义检查循环时使用in运算符。

def carsaction(instructions):
    """
    Fonction servant à faire un choix pour interagir avec soi même.
    """
    user_input = str(None)
    while user_input not in instructions:
        user_input = input("Your input: ")
        if user_input in instructions:
            break
        else:
            print("not valid")
            continue




carsaction(["a","b","c"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM