2017-10-12 75 views
0

繼承人我的代碼片段。它不會說用戶不正確。每個問題的答案在列表中以相同的順序排列。在Python中遇到隨機數問題

題庫

 questions = ["45 - 20","32 - 12","54 + 41"] 

     # Answer Bank 
     answers = ["25","20","95"] 


     while qleft != 0: 


      # Get random question 
      qnumber = randint(0,2) 
      currentquestion = questions[qnumber] 
      currentanswer = answers[qnumber] 

      # Question 
      userchoice = int(input("What does {} equal? ".format(currentquestion))) 

      # Check Answer 
      if userchoice != currentanswer: 
       print("Incorrect") 
       qleft -= 1 
      elif userchoice == currentanswer: 
       print("Correct") 
       qleft -= 1 

      else: 
       print("That's not a valid answer") 
+0

看起來像'integer!= string'對我來說經典的例子... – Shadow

回答

1

用戶的答案,userchoice,是一個整數,但實際的答案,currentanswer是一個字符串。它會工作,如果你只是離開了輸入作爲一個字符串:

questions = ["45 - 20","32 - 12","54 + 41"] 

    # Answer Bank 
    answers = ["25","20","95"] 


    while qleft != 0: 


     # Get random question 
     qnumber = randint(0,2) 
     currentquestion = questions[qnumber] 
     currentanswer = answers[qnumber] 

     # Question 
     userchoice = input("What does {} equal? ".format(currentquestion)) 

     # Check Answer 
     if userchoice != currentanswer: 
      print("Incorrect") 
      qleft -= 1 
     elif userchoice == currentanswer: 
      print("Correct") 
      qleft -= 1 

     else: 
      print("That's not a valid answer") 
+0

當別人指出它的時候很明顯! –

2

你有str的答案,這是從來沒有平等的比較的int輸入。

如果你想處理整數,改變

answers = ["25","20","95"] 

answers = [25,20,95] 

,它會工作。

或者,不要將input()的結果轉換爲int

0

這裏的區別是:

import random as r 

    questions = ["45 - 20","32 - 12","54 + 41"] 

    # Answer Bank 
    answers = [25,20,95] 

    qleft = 3 

    while qleft != 0: 


     # Get random question 
     qnumber = r.randint(0,2) 
     currentquestion = questions[qnumber] 
     currentanswer = answers[qnumber] 

     # Question 
     userchoice = int(input("What does {} equal? ".format(currentquestion))) 

     # Check Answer 
     if userchoice != currentanswer: 
      print("Incorrect") 
      qleft -= 1 
     elif userchoice == currentanswer: 
      print("Correct") 
      qleft -= 1 

     else: 
      print("That's not a valid answer") 

通知,「25」 = 25

0

既然要轉換的用戶的回答爲int,正確的答案也東東爲int!否則,你將字符串與int進行比較,它永遠不會相等。

answers = [25, 20, 95]