import random
print "小学四则运算测试(输入0000退出):"
ops = ['+', '-', '*', '/'] # 运算符
ans = "" # 用户回答
i = 1 # 题号
while ans != "0000":
add1 = random.randint(1, 10) # 数1
add2 = random.randint(1, 10) # 数2
op = random.randint(0, 3) # 随机运算符
eq = str(add1) + ops[op] + str(add2) # 算式
val = eval(eq) # 算式答案
print "Q%d: %s=" %(i,eq) # 输出提问
ans = raw_input("A: ") # 用户回答
if ans == '0000': # 退出循环
break
elif val == int(ans): # 正确
print "right!"
else: # 错误
print "error. the right answer is %d" % val
i += 1 # 更新题号
演示示例: