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分。
答案 0 :(得分:1)
您并不总是将输入转换为整数。
当op == '*'
或op == '+'
时,您尝试与input()
返回的字符串进行比较:
guess2 = input("")
与数字的字符串比较永远不会相等。对于op == '-'
,您首先正确地将答案转换为整数:
guess1 = int(input(""))
你的循环也被破坏了;你循环一个包含两个值的元组:
for x in (0, 10):
而不是超出范围:
for x in range(0, 10):
你可以避免在代码中重复这么多重复;计算表达结果并在一个位置询问答案;这样就可以减少出错的地方。
答案 1 :(得分:1)
此
for x in (0,10):
...
运行代码(...
)两次:一次将x
设置为0,第二次将x
设置为10.
你真正想要的是:
for x in range(10):
...
然后x
将为0,1,...,9,代码运行10次。