python小学口算题库生成器
时间: 2023-11-16 19:04:44 浏览: 41
以下是一个简单的Python口算题库生成器的示例代码,可以根据用户的需求生成指定数量和范围的加减乘除口算题,并将题目和答案保存到指定的文件中:
```python
import random
def generate_question(num, op, max_num):
"""
生成口算题
:param num: 题目数量
:param op: 运算符,可选值为'+', '-', '*', '/'
:param max_num: 参与运算的最大数值
:return: 返回包含题目和答案的列表
"""
questions = []
for i in range(num):
a = random.randint(1, max_num)
b = random.randint(1, max_num)
if op == '+':
ans = a + b
elif op == '-':
ans = a - b
elif op == '*':
ans = a * b
elif op == '/':
ans = a // b
a = ans * b # 保证除法的整除性
else:
raise ValueError('不支持的运算符')
questions.append(f'{a} {op} {b} = ')
questions.append(str(ans))
return questions
# 生成10道100以内的加法题
questions = generate_question(10, '+', 100)
with open('questions.txt', 'w') as f:
f.write('\n'.join(questions))
```
运行以上代码后,会在当前目录下生成一个名为`questions.txt`的文件,其中包含了10道100以内的加法题和它们的答案。