2014-12-02 45 views
-2

我正在做一個簡單的數學測驗其工作正常,除非當我問如果它的正確答案它總是說錯誤,如果它的正確與否。我不知道我錯了什麼地方的任何幫助,將不勝感激。總是說錯了嗎?

import random 
QuestN = 1 
QNC = 0 
CS = 0 
WS = 0 

while True: 
    #Number Of Questions: 
    QNC = QNC + 1 
    if QNC == 10: 
     break 

    #Choosing The Questions 
    ops = ['+', '-', '*', '/'] 
    num1 = random.randint(0,12) 
    num2 = random.randint(1,10) 
    operation = random.choice(ops) 

    #Simplifying The Operations 
    if operation == "+": 
     NEWOP = "+" 
    elif operation == "-": 
     NEWOP = "-" 
    elif operation == "*": 
     NEWOP = "x" 
    elif operation == "/": 
     NEWOP = "÷" 

    #Asking The Questions 
    print("Awnser This:") 
    print(num1) 
    print(NEWOP) 
    print(num2) 
    maths = eval(str(num1) + operation + str(num2)) 

    #Awnsering The Questions 
    PLAYERA = input(": ") 
    print(maths) 
    #Keeping Score 
    if PLAYERA == maths: 
     print("Correct") 
     CS = CS +1 
    else: 
     print("Incorrect") 
     WS = WS +1 
    print() 

#RESTART 
+0

無關的評論:這將只運行'9'次,因爲你在檢查之前遞增'QNC'。如果你想要'10'的問題,你應該在檢查行之後移動增量行,或者將檢查改爲'if QNC> 10:'。 – gcarvelli 2014-12-02 22:06:22

回答

1

變量PLAYERA將是一個字符串。變量maths將是一個整數。在Python中,"7"7不同,因此您的if語句永遠不會成立。

你因此也需要這樣的:

if int(PLAYERA) == maths: 
    print("Correct") 
    CS = CS +1 

注意,該代碼會導致錯誤它玩家的輸入是不是數字。你可以通過這樣做來避免這種情況:

if PLAYERA == str(maths): 
    print("Correct") 
    CS = CS +1 
+2

因爲用戶理論上可以輸入他或她想要的任何東西,所以這樣做更安全:'如果PLAYERA == str(數學):' – gcarvelli 2014-12-02 22:02:30

+0

@ killermonkey50好點,雖然安全似乎不是太多考慮到自由使用'eval'問題! – rlms 2014-12-02 22:03:20

+0

頻繁?他只用它一次! ,P – HarryCBurn 2014-12-02 22:07:04