给娃来点计算题吧

娃刚学数学,20以内进位退位计算老是出错,那老父亲就给你多来点题目加强训练一下吧。。。

import random
# pip install python-docx
from docx import Document
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING

def generate_addition():
  # 加法:两个个位数相加,结果大于10
  while True:
    a = random.randint(1, 9)  # 个位数
    b = random.randint(1, 9)  # 个位数
    if a + b > 10:  # 结果大于10
      return f"{a} + {b} = "

def generate_subtraction():
  # 减法:大于10小于20的数减去个位数,结果是个位数
  while True:
    a = random.randint(11, 19)  # 大于10小于20
    b = random.randint(1, 9)    # 个位数
    result = a - b
    if result >= 1 and result <= 9:  # 结果是个位数
      return f"{a} - {b} = "

def generate_question(used_questions):
  # 随机选择加法或减法,确保不重复
  while True:
    if random.choice([True, False]):
      question = generate_addition()
    else:
      question = generate_subtraction()
    
    if question not in used_questions:
      used_questions.add(question)
      return question

def create_page(doc):
  # 页头
  p = doc.add_paragraph()
  p.add_run("       姓名:__________    日期:__________    用时:__________    得分:__________").bold = True
  p.alignment = WD_ALIGN_PARAGRAPH.CENTER
  # 设置页头字体大小
  for run in p.runs:
    run.font.size = Pt(12)

  # 添加更多空行来增加间距
  for _ in range(2):
    doc.add_paragraph()

  # 题目表格
  table = doc.add_table(rows=10, cols=4)
  table.autofit = True
  
  # 设置表格行高以撑满页面
  for row in table.rows:
    row.height = Inches(0.6)  # 增加行高
  
  # 用于跟踪当前页面已使用的题目,避免重复
  used_questions = set()
  
  for i in range(10):
    for j in range(4):
      cell = table.cell(i, j)
      cell.text = generate_question(used_questions)
      # 增加字体大小
      cell.paragraphs[0].runs[0].font.size = Pt(16)
      cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
      # 设置行距为2.25倍
      paragraph_format = cell.paragraphs[0].paragraph_format
      paragraph_format.line_spacing_rule = WD_LINE_SPACING.MULTIPLE
      paragraph_format.line_spacing = 2.25
  

def main():
  pages = int(input("请输入需要生成的页数:"))
  doc = Document()
  for page_num in range(1, pages + 1):
    create_page(doc)
    if page_num != pages:
      doc.add_page_break()
  doc.save("计算题.docx")
  print("已生成文件:计算题.docx")

if __name__ == "__main__":
  main()

要多少页生成多少页,生成完的word文件直接打印就行了。

怎么样,是不是很棒呢?

posted @ 2025-08-08 12:22  黑月教主  阅读(17)  评论(0)    收藏  举报