我如何让我的python代码工作?随机数学测验

时间:2015-02-22 16:37:11

标签: python math random slickquiz

这是我的代码,它必须在代码中有+ - *,它必须随机选择,但它不起作用它没有说正确的答案,我将不胜感激任何帮助,谢谢。

import random
import operator
question_number = 0
score = 0

ops = {'+':operator.add,
           '-':operator.sub,
           '*':operator.mul,
           '/':operator.truediv}
number1 = random.randint(0,12)
number2 = random.randint(1,10)
op = random.choice(list(ops.keys()))

print ("this is a short maths quiz")
name = input ("what is your name")
age = input ("how old are you " +name)
print ("ok "+name+" im going to start the quiz now")
print(number1, op, number2)
user_input=int(input())
answer = (number1,op,number2)
if user_input == answer:
    print("Well done")
    score = score + 1

else:
    print("WRONG!")
    print("The answer was",answer)

question_number = question_number + 1

2 个答案:

答案 0 :(得分:0)

您需要op作为密钥才能从ops字典中获取适当的值,并call将其与两个数字相对应:

answer = ops[op](number1, number2)

您的代码正在将int与元组进行比较,即9 == (3, '+', 6)

除非您想要负数,否则您可能还希望在左侧保留较大的数字,在右侧保持较小的数字。

answer = ops[op](max(number1,number2),min(number1, number2))

除非这是一个while循环question_number = question_number + 1,否则不会做太多。

答案 1 :(得分:0)

你需要使op成为op而不是字符串。 这是你的代码修复。

string comment = null;
comment += "<ul class='bxslider'>";
for (int i = 0; i < dt.Rows.Count; i++)
{
    comment += "<li>";
    ....
    comment += "</li>";
}
comment += "</ul>";

您可以添加import random import operator question_number = 0 score = 0 ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv} number1 = random.randint(0,12) number2 = random.randint(1,10) op = random.choice(list(ops.keys())) print ("this is a short maths quiz") name = input ("what is your name") age = input ("how old are you " +name) print ("ok "+name+" im going to start the quiz now") print(number1, op, number2) user_input=int(input()) if op == "+": answer = (number1+number2) elif op == "-": answer = (number1-number2) elif op == "*": answer = (number1*number2) elif op == "/": answer = (number1/number2) if user_input == answer: print("Well done") score = score + 1 else: print("WRONG!") print("The answer was",answer) question_number = question_number + 1 循环以重复