前言:假期中,许多小学老师要求每天要给学生出一定数量的题目,供学生练习,然后给学生检查,十分麻烦。
import random
# 用来计算最终结果
def calculation_formula(a,b,c,c1,c2):
if c1 == '+':
num = a+b
else:
num = a-b
if c2 == '+':
num = num+c
else :
num = num-c
return num
def random_formula():
a = random.randint(0, 100)
b = random.randint(0, 100)
c = random.randint(0, 100)
op = ['+', '-']
c1 = random.choice(op)
c2 = random.choice(op)
# 生成式子
formula = str(a) + c1 + str(b) + c2 + str(c)
re = calculation_formula(a,b,c,c1,c2)
string = formula+'='+str(re)
# 防止出现负数
if re < 0:
random_formula()
else:
# print(formula,'=',re)
# 将生成的算式写到文件中去
with open(r'C:\Users\lch20\Desktop\math\01.txt','a',encoding='utf-8') as f:
f.write(string)
# 为了美观
f.write('\n')
pass
# 生成25个100以内的加减混合运算
for i in range(25):
random_formula()
pass