用到了两个库:random、docx
# coding=utf-8
'''
习题自动生成工具
自动生成数学练习题,包含加减乘除,不规定数值范围,
由传入的参数(10:10以内;100:100以内)决定。
要求1:输入:生成习题数量N,习题范围:M;输出:
将生成的习题保存到question(word格式)中,
对应的答案保存到answer(word格式)中。
'''
import random
import docx
N = int(input("请输入需要生成的题的数量:\n"))
M = int(input("请输入习题范围(10或100):\n"))
print('生成{}道题,习题范围为;{}以内\n'.format(N, M))
i = 0
answer=[]
question=[]
if M == 10:
while (i != N):
a = random.randint(1, 10)
b = random.randint(1, 10)
str = random.choice('+-*/')
i += 1
if (str == '+'):
c = a + b
elif (str == '-'):
c = a - b
elif (str == '*'):
c = a * b
elif (str == '/'):
d = a // b
e = a % b
c = '{}...{}'.format(d, e)
#print('({}) {}{}{}={}\n'.format(i, a, str, b, c))
answer.append('({}) {}{}{}={}'.format(i, a, str, b, c))
question.append('({}) {}{}{}=_____'.format(i,a,str,b))
elif M == 100:
while (i != N):
a = random.randint(1, 100)
b = random.randint(1, 100)
str = random.choice('+-*/')
i += 1
c=''
if (str == '+'):
c = a + b
elif (str == '-'):
c = a - b
elif (str == '*'):
c = a * b
elif (str == '/'):
d = a // b
e = a % b
c = '{}...{}'.format(d, e)
# print('({}) {}{}{}={}\n'.format(i, a, str, b, c))
answer.append('({}) {}'.format(i, c))
question.append('({}) {}{}{}=_____'.format(i, a, str, b))
doc_question = docx.Document()
for i in question:
print(i)
doc_question.add_paragraph(i)
doc_question.save('question.docx')
doc_answer=docx.Document()
for i in answer:
print(i)
doc_answer.add_paragraph(i)
doc_answer.save('answer.docx')
仅供参考。