2017-08-04 63 views
1

從我對Python完全不熟悉開始,我必須做一個學校項目,並且我堅持使用這部分代碼。很大程度上,IF語句需要滿足這些要求(用戶輸入等於答案,我確信這一點),系統直接跳到ELSE。我不確定我是否只是盲目的,這是一個簡單的格式問題,或者如果它是我失蹤的其他東西。IF語句直接跳到其他語句

while valid == False: 
topic = input().lower() 
if topic == "addition": 
    print ("You have selected Addition!") 
    valid = True 

    ARand1 = randrange(1, 200) 
    ARand2 = randrange(1, 200) 
    question_answer = ARand1 + ARand2 

    print ("Question",questions_asked,":") 
    print ("What is",ARand1,"+",ARand2,"?") 

    users_answer = input("Please input your answer") 

    if users_answer == (question_answer): 
     print ("Correct!") 
     total_score += 1 
     questions_asked += 1 

    else: 
     print ("Incorrect!") 
     questions_asked += 1 
     print (questions_asked) 


elif topic == "subtraction": 
    print ('You have selected Subtraction!') 
    valid = True 

    SRand1 = randrange(100, 200) 
    SRand2 = randrange(1, 100) 
    answer = SRand1 - SRand2 

    print ("Question",questions_asked,":") 
    print ("What is",SRand1,"-",SRand2,"?") 

我被卡住的部分是第二條if語句(如users_answer ==(question_answer):)。即使滿足條件,它也會完全跳過IF並直接進入ELSE。

道歉,如果它是簡單的或如果這寫得不好,我幾個星期前剛剛介紹給Python。

+3

'users_answer'總是一個字符串......'question_answer'是一個整數。他們不是同一類型,所以不是平等的 –

回答

2

變化users_answer = input("Please input your answer")users_answer = raw_input("Please input your answer") 如果答案,是一個int,解析它作爲int(raw_input("Please input your answer"))

引用此答案here 輸入():解釋並評估輸入,這意味着如果用戶輸入整數的整數,將返回,如果用戶輸入字符串,則返回字符串。 raw_input():raw_input()正好接受用戶輸入的內容並將其作爲字符串傳回。它不解釋用戶輸入。即使輸入了10的整數值或輸入了列表,它的類型也將是隻有字符串。