自动生成三位数加减法并导出docx格式
孩子学校要求每天100道三位数加减法,于是,写了段python小代码实现。实现:
1、随机生成100道三位数加减法
2、计算结果介于0和1000之间
3、导出docx的word格式,每页4列,每列25道,共100道
from docx import Document
import random
def generate_question():
num1 = random.randint(100, 999)
num2 = random.randint(100, 999)
operator = random.choice(['+', '-'])
# 保证结果在0到1000之间
if operator == '+':
answer = num1 + num2
while answer > 1000:
num1 = random.randint(100, 999)
num2 = random.randint(100, 999)
answer = num1 + num2
else:
answer = num1 - num2
while answer < 0:
num1 = random.randint(100, 999)
num2 = random.randint(100, 999)
answer = num1 - num2
question = f"{num1} {operator} {num2} = "
return question, answer
def generate_questions(num_questions):
questions = []
for _ in range(num_questions):
question, answer = generate_question()
questions.append((question, answer))
return questions
def save_to_docx(questions, filename):
document = Document()
table = document.add_table(rows=25, cols=4)
row_index = 0
col_index = 0
for question, _ in questions:
cell = table.cell(row_index, col_index)
cell.text = question
col_index += 1
if col_index == 4:
col_index = 0
row_index += 1
if row_index == 25:
row_index = 0
document.add_page_break()
document.save(filename)
if __name__ == "__main__":
num_questions = 100
questions = generate_questions(num_questions)
save_to_docx(questions, "math_questions.docx")
注意:
1、需要pip install python-docx
2、本代码借助cgpt实现
3、每天一百道足够了,不要给孩子更多压力,都不容易 学习了,谢谢分享
页:
[1]