为了给孩子出计算题,老父亲花了十分钟写了个Python自动出题,20以内加减法以及考察99表的乘除法。
打印结果后粘贴到Word,调整一下格式。
if __name__ == '__main__':
import random
for i in range(0,10):
s = ""
for i in range(0, 3):
type = random.randint(1, 4)
if type == 1:
a = random.randint(1, 20)
b = random.randint(1, 20)
s += "%3d + %3d = " % (a, b)
elif type == 2:
a = random.randint(1, 20)
b = random.randint(1, 20)
if a < b:
tmp = a
a = b
b = tmp
s += "%3d - %3d = " % (a, b)
elif type == 3:
a = random.randint(2, 9)
b = random.randint(2, 9)
s += "%3d x %3d = " % (a, b)
elif type == 4:
a = random.randint(2, 9)
b = random.randint(2, 9)
s += "%3d / %3d = " % (a * b, b)
else:
print ('type is %d' % type)
print (s)
再写一个版本,出题加回答。
import random
import sys
def get_r_opr():
i = random.randint(0, 3)
if i == 0:
return "+"
elif i == 1:
return "-"
elif i == 2:
return "*"
else:
return "/"
if __name__ == '__main__':
while True:
x = random.randint(0, 100)
y = random.randint(0, 100)
z = random.randint(0, 100)
op1 = get_r_opr()
op2 = get_r_opr()
type = random.randint(0, 1)
if type == 0:
expression = "%s %s %s %s %s" % (x, op1, y, op2, z)
else:
expression = "%s %s %s" % (x, op1, y)
ret = eval(expression)
if ret < 0 or int(ret) != ret or ("*" in expression and ret > 100):
continue
print("%s = ? " % expression)
correct = False
while not correct:
answer = input("请输入答案(输入q后回车可退出程序, 输入s后回车可跳过此题):")
if answer.lower() == "s":
correct = True
continue
if answer.lower() == "q":
sys.exit()
try:
answer = int(answer)
except Exception as ex:
print("必须输入整数答案")
continue
if answer != int(ret):
print("不对")
continue
else:
print("恭喜,正确。")
correct = True