在Python中遇到随机数问题

问题描述:

继承人我的代码片段。它不会说用户不正确。每个问题的答案在列表中以相同的顺序排列。在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

用户的答案,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

当别人指出它的时候很明显! –

你有str的答案,这是从来没有平等的比较的int输入。

如果你想处理整数,改变

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

answers = [25,20,95] 

,它会工作。

或者,不要将input()的结果转换为int

这里的区别是:

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

既然要转换的用户的回答为int,正确的答案也东东为int!否则,你将字符串与int进行比较,它永远不会相等。

answers = [25, 20, 95]