python实现随机生成小学数学题目并输出到word

以下是一个简单的Python程序,可以生成小学数学题目并将其输出到Word文档:

import random
from docx import Document
from docx.shared import Pt

def generate_question():
    # 随机生成两个整数和一个运算符
    num1 = random.randint(0, 100)
    num2 = random.randint(0, 100)
    operator = random.choice(['+', '-', '*', '/'])

    # 根据运算符生成题目和答案
    if operator == '+':
        question = f'{num1} + {num2} ='
        answer = num1 + num2
    elif operator == '-':
        question = f'{num1} - {num2} ='
        answer = num1 - num2
    elif operator == '*':
        question = f'{num1} × {num2} ='
        answer = num1 * num2
    elif operator == '/':
        # 避免除数为零,重新生成随机数
        while num2 == 0:
            num2 = random.randint(0, 100)
        question = f'{num1} ÷ {num2} ='
        answer = round(num1 / num2, 2)  # 保留两位小数

    return question, answer

if __name__ == '__main__':
    # 创建一个Word文档
    document = Document()
    
    # 设置字体样式和大小
    font = document.styles['Normal'].font
    font.name = '微软雅黑'
    font.size = Pt(16)

    # 生成20道数学题目
    for i in range(20):
        question, answer = generate_question()
        # 在文档中添加题目和答案
        document.add_paragraph(f'{i+1}. {question} {answer}', style='Normal')

    # 保存文档
    document.save('math_questions.docx')

这个程序使用了Python的random模块来生成随机数和随机运算符,然后根据不同的运算符生成不同的数学题目。这些题目和答案使用Python的docx模块输出到Word文档中。您可以根据需要修改程序中的字体样式和题目数量。要运行程序,请将它保存为.py文件并在命令行中输入python filename.py命令。程序将在当前目录下创建一个名为math_questions.docx的Word文档,其中包含生成的数学题目。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忧伤的玩不起

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值