简洁的用Python写小学生数学四则运算练习游戏
时间: 2024-04-25 18:16:22 浏览: 71
这是一个简单的小学生数学四则运算练习游戏,可以让小学生练习加减乘除运算。
```python
import random
# 生成随机数
def generate_number():
return random.randint(1, 10)
# 生成随机运算符
def generate_operator():
operators = ['+', '-', '*', '/']
return random.choice(operators)
# 计算表达式的值
def calculate_result(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
# 主程序
def main():
correct_answers = 0
num_questions = 5
for i in range(num_questions):
num1 = generate_number()
num2 = generate_number()
operator = generate_operator()
expression = str(num1) + operator + str(num2) + '='
user_answer = input(expression)
expected_answer = str(calculate_result(num1, num2, operator))
if user_answer == expected_answer:
print('Correct!')
correct_answers += 1
else:
print(f'Incorrect! The correct answer is {expected_answer}.')
print(f'You answered {correct_answers} out of {num_questions} questions correctly.')
if __name__ == '__main__':
main()
```
运行结果:
```
3+7=10
Correct!
5+7=12
Correct!
5+5=10
Correct!
5-1=4
Correct!
8*7=56
Correct!
You answered 5 out of 5 questions correctly.
```
阅读全文