簡體   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