请用python完成一个答题小程序。功能要求:随机生成几道简单的算数题,根据答题正确与否进行分数计算。
时间: 2024-10-18 18:03:19 浏览: 33
当然可以,我们可以使用Python的random模块来生成随机的数学题目,用户输入答案后检查是否正确并更新分数。这是一个简单的示例:
```python
import random
def generate_question():
operators = ['+', '-', '*', '/']
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
operator = random.choice(operators)
if operator == '+':
correct_answer = num1 + num2
elif operator == '-':
correct_answer = num1 - num2
elif operator == '*':
correct_answer = num1 * num2
else: # division
correct_answer = round(num1 / num2) # 四舍五入防止除不尽的情况
question = f"{num1} {operator} {num2}"
return question, correct_answer
def check_answer(question, user_answer):
_, correct_answer = generate_question() # 使用上一次生成的正确答案
if int(user_answer) == correct_answer:
print("答对了!")
return True
else:
print(f"错了,正确答案是{correct_answer}")
return False
def play_quiz():
score = 0
num_questions = 5 # 设定题目数量
for _ in range(num_questions):
question, correct_answer = generate_question()
user_answer = input(question + "请输入你的答案:")
if check_answer(question, user_answer):
score += 1
print(f"总分:{score}/{num_questions}")
play_quiz()
```
在这个程序中,我们首先定义了一个`generate_question()`函数用于生成加减乘除的算术题。然后`check_answer()`函数负责验证用户答案。`play_quiz()`函数则控制游戏流程,让用户连续回答几个问题,并根据答案得分。
阅读全文