口算练习程序python
时间: 2023-09-28 07:03:49 浏览: 115
以下是一个简单的口算练习程序的Python代码:
```python
import random
def generate_question():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
operator = random.choice(['+', '-', '*', '/'])
if operator == '+':
answer = num1 + num2
elif operator == '-':
answer = num1 - num2
elif operator == '*':
answer = num1 * num2
else:
answer = round(num1 / num2, 2) # 保留两位小数
question = f"What is {num1} {operator} {num2}?"
return question, answer
def main():
score = 0
num_questions = 5
for i in range(num_questions):
question, answer = generate_question()
print(question)
user_answer = input("Your answer: ")
try:
if float(user_answer) == answer:
print("Correct!")
score += 1
else:
print(f"Incorrect. The answer is {answer}.")
except ValueError:
print("Invalid input. Please enter a number.")
print(f"You scored {score} out of {num_questions}.")
if __name__ == '__main__':
main()
```
运行程序后,它会生成 5 个简单的口算题,每个题目都包括两个随机数和一个随机运算符,然后让用户输入答案。用户输入后,程序会判断答案是否正确,并给出相应的反馈。最后,程序会输出用户的得分。
阅读全文