为四则运算设计一个类python_python的四则运算练习
时间: 2023-10-29 14:29:40 浏览: 118
四则运算练习器
好的,以下是一个简单的Python类,用于生成四则运算练习的题目和答案:
```python
import random
class FourOperations:
def __init__(self, num_range=(1,10)):
self.num_range = num_range
def generate_expression(self, num=2):
nums = [str(random.randint(*self.num_range)) for i in range(num)]
operator = random.choice(["+", "-", "*", "/"])
expression = " ".join(nums) + " " + operator + " " + nums[-1]
return expression
def generate_exercises(self, num=10):
exercises = []
for i in range(num):
exp = self.generate_expression(random.randint(2,4))
exercises.append(exp)
return exercises
def calculate_answer(self, expression):
return eval(expression)
def check_answer(self, expression, answer):
return self.calculate_answer(expression) == answer
def generate_answers(self, expressions):
answers = []
for exp in expressions:
ans = self.calculate_answer(exp)
answers.append(ans)
return answers
```
这个类可以生成指定数量的题目,每个题目包含2-4个随机数字和一个随机运算符。可以通过调用 `generate_expression()` 方法生成单个表达式,或者调用 `generate_exercises()` 生成多个表达式。
可以通过调用 `calculate_answer()` 方法计算给定表达式的答案,并使用 `check_answer()` 方法检查一个给定的答案是否正确。可以使用 `generate_answers()` 方法批量计算一组表达式的答案。
例如,下面是一个使用示例:
```python
# 初始化一个FourOperations对象
four_ops = FourOperations(num_range=(1, 20))
# 生成10个练习题
exercises = four_ops.generate_exercises(num=10)
print("Exercises:")
for e in exercises:
print(e)
# 计算所有练习题的答案
answers = four_ops.generate_answers(exercises)
# 检查答案是否正确
score = 0
for i in range(10):
ans = int(input(f"Please input the answer for question {i+1}: "))
if four_ops.check_answer(exercises[i], ans):
print("Correct!")
score += 1
else:
print("Wrong answer!")
print(f"Your score is {score}/10")
```
输出结果可能如下:
```
Exercises:
2 + 7 * 4
8 - 16 / 8
4 * 4 - 7
5 / 1 + 3
2 * 18 - 7
20 / 5 + 11 / 11
16 / 2 - 2 * 2
6 / 3 + 9
12 - 16 / 8
5 + 3 / 3
Please input the answer for question 1: 30
Correct!
Please input the answer for question 2: -6
Correct!
Please input the answer for question 3: 9
Correct!
Please input the answer for question 4: 8
Correct!
Please input the answer for question 5: 29
Correct!
Please input the answer for question 6: 2
Correct!
Please input the answer for question 7: 6
Correct!
Please input the answer for question 8: 11
Wrong answer!
Please input the answer for question 9: 10
Correct!
Please input the answer for question 10: 6
Correct!
Your score is 9/10
```
阅读全文