尝试和除外,当输入错误数据时,需要问题不是随机的

时间:2016-02-09 23:05:55

标签: python math

这是一个数学测验,在我的尝试中除了我需要重复相同的问题,如果输入了错误或无效的数据,但它会随机提供。

继承我的代码

import random

count = 0
score = 0
name = input("What is your name?: ")
print ("Hello",name,"welcome to the arithmetic quiz")

while count < 10:
  while True:
      try:
          num1 = random.randint(1, 10)
          num2 = random.randint(1, 10)
          operator = random.choice(["+", "-", "*"])
          print("What is: ", num1, operator, num2)
          user = int(input(" "))
          break
      except ValueError:
          print("That is invalid, enter your answer again: ") 

  if operator == "+":
                answer = num1 + num2
  elif operator == "-":
                answer = num1 - num2
  elif operator == "*":
                answer = num1 * num2

  if user == answer:
    print("Correct")
    score = score + 1
    count = count + 1
  else:
    print("Incorrect")
    count = count + 1

print(name, "You got", score, "out of 10")

1 个答案:

答案 0 :(得分:1)

while count < 10:

    num1 = random.randint(1, 10)
    num2 = random.randint(1, 10)
    operator = random.choice(["+", "-", "*"])

    while True:
        try:
            print("What is: ", num1, operator, num2)
            user = int(input(" "))
            break

        except ValueError:
            print("That is invalid, enter your answer again: ")