四则运算题库python代码
时间: 2023-06-21 21:09:23 浏览: 109
以下是一个简单的四则运算题库 Python 代码,可以随机生成指定数量的四则运算题目:
```python
import random
OPERATORS = ["+", "-", "*", "/"]
def generate_question():
operator = random.choice(OPERATORS)
if operator == "/":
a = random.randint(1, 100)
b = random.randint(1, 10)
a = a * b
else:
a = random.randint(1, 100)
b = random.randint(1, 100)
question = f"{a} {operator} {b}"
answer = eval(question)
return question, answer
if __name__ == "__main__":
num_questions = int(input("请输入题目数量:"))
questions = []
for i in range(num_questions):
question, answer = generate_question()
questions.append((question, answer))
print("题目:")
for i, (question, answer) in enumerate(questions):
print(f"{i+1}. {question} = ")
print("答案:")
for i, (question, answer) in enumerate(questions):
print(f"{i+1}. {answer}")
```
使用方法:
1. 运行代码后,会提示你输入题目数量。
2. 然后程序会生成指定数量的四则运算题目和答案,并输出到屏幕上。
注意:此代码中没有做除法运算的除数不能为0的检查,可以根据需要进行添加。
阅读全文