它给出了正确的答案,有时给出了错误的答案

  • 本文关键字:答案 错误 python loops math
  • 更新时间 :
  • 英文 :

print("Hello, and welcome to the Maths quiz!/n")
#Asks user for name - 05/03/2015
name = input("What is your name?")
#This will import random to generate random functions
import random
#This is a variable for score
#It has been set to 0 at the start of the program
score = 0
#This creates an array containing the mathematical operators
#that this quiz will use
ops = ['+','-','*']
#A loop has been set for 0 - 10
for x in (0,10):
    #This is variable has been set to the operator of the equation that
    #uses the random function and will choose a random operator from the
    #array containing the operators made earlier
    op = random.choice(ops)
    if op == '+':
        left1 = random.randint(1,100)
        right1 = random.randint(1,100)
        print (str(left1) + op + str(right1))
        answer  = eval(str(left1) + op + str(right1))
        guess = input("")
        if guess == answer:
            print("Correct!")
            score += 1
        else:
            print ("Incorrect")
    elif op == '-':
        left2 = random.randint(1,100)
        right2 = random.randint(1,100)
        print (str(left2) + op + str(right2))
        answer1 = eval(str(left2) + op + str(right2))
        guess1 = int(input(""))
        if answer1 == guess1:
            print("Correct!")
            score += 1
        else:
            print("Incorrect")
    elif op == '*':
        left3 = random.randint(1,100)
        right3 = random.randint(1,100)
        print (str(left3) + op + str(right3))
        answer2 = eval(str(left3) + op + str(right3))
        guess2 = input("")
        if answer2 == guess2:
            print("Correct!")
            score += 1
        else:
            print("Incorrect")
    else:
        break
print (score)

当我这样做时,它会生成一个随机测验,该测验只循环两次,即使我希望它循环 10 次。此外,它有时会给出正确的答案,有时给出错误的答案。例如:

Hello, and welcome to the Maths quiz!/n
What is your name?j
95*3
285
Incorrect
35-46
-11
Correct!

我想做的是使用加法、减法和乘法运算符生成随机算术问题。另外,让它循环 10 次,最后给出 10 分。

for x in (0,10):
    ...

运行代码 ( ... ) 两次:一次将x设置为 0,第二次将x设置为 10。

你真正想要的是这个:

for x in range(10):
    ...

然后x将为 0、1、...、9,代码运行 10 次。

您并不总是将输入转换为整数。

op == '*'op == '+'时,您尝试与从input()返回的字符串进行比较:

guess2 = input("")

字符串与数字的比较永远不会相等。对于op == '-',您首先正确地将答案转换为整数:

guess1 = int(input(""))

你的循环也被破坏了;你正在循环一个包含两个值的元组:

for x in (0, 10):

而不是超过一个范围:

for x in range(0, 10):

你最好避免在代码中重复太多;计算表达式结果并在一个地方询问答案;这样犯错误的地方就更少了。

最新更新