簡體   English   中英

Python測驗游戲邏輯錯誤

[英]Python Quiz Game Logic Error

我正在嘗試練習python,因為我即將在12歲開始。 我創建了一個問答游戲,但是當我正確回答問題時,總是說錯了

print("Welcome to the math quiz game!")
for i in range(0,10):
    operators = ['+','-','*','/']
    import random
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)
    randop = random.choice(operators)
    question = input("What is %d %s %d: " % (num1,randop,num2))
    if randop == "+":
        answer = num1 + num2
    elif randop == "-":
        answer = num1 - num2
    elif randop == "*":
        answer = num1 * num2
    elif randop == "/":
        answer = num1 / num2
    if question == answer:
        print("\nCorrect")
    elif question != answer:
        print("Incorrect or Invalid")

在使用==的程序中進行比較時,我們必須比較兩個相同類型的變量(在啟動Python時可能是vious回的)。 Answer是一個數字,而question是一個由用戶編寫的字符串。 因此,Python將兩者視為不同和錯誤。 為避免這種情況,您必須將數字轉換為字符串或將字符串轉換為數字,以便比較兩個相同類型的變量。

如前所述,您需要將input()的返回值轉換為浮點數(以應付除法input()小數):

question = float(input("What is %d %s %d: " % (num1,randop,num2)))

我不建議這樣做,因為輸入錯誤會導致游戲崩潰,因此請使用帶有try/except塊的輸入驗證:

question = input("What is %d %s %d: " % (num1,randop,num2))
try:
    question = float(question)
except ValueError:
    print('Invalid or incorrect.')
    continue # skip the rest of the code and head straight into the next iteration in the for loop

另外,我也不建議您使用除法選項,因為大多數值將是重復的小數,除非您事先檢查答案不會重復或將答案四舍五入到小數點后兩位,否則不能正確輸入用戶輸入2 dp的答案

(您也可以將'answer'變量設置為字符串,而不是將'question'設置為整數)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM