用python随机生成20以内的10道加减法计算题,并统计做对的个数,用户来控制是否结束。考虑异常处理负数等一些数据的输入。
时间: 2024-05-03 08:20:04 浏览: 184
非常好的问题,我可以回答!以下是代码示例:
```python
import random
score = 0
completed = False
while not completed:
num1 = random.randint(0, 20)
num2 = random.randint(0, 20)
operator = random.choice(['+', '-'])
if operator == '+':
answer = num1 + num2
question = f"{num1} + {num2}"
else:
answer = num1 - num2
question = f"{num1} - {num2}"
try:
user_answer = int(input(f"{question} = "))
if user_answer == answer:
score += 1
print("恭喜,答对了!")
else:
print("很遗憾,答错了,正确答案是:", answer)
except ValueError:
print("请您输入一个整数!")
choice = input("是否继续做题?(y/n)")
if choice.lower() == 'n':
completed = True
print("你一共做对了", score, "道题目!")
```
希望这个示例程序能够帮助到你,还有什么问题可以继续问我哦。
阅读全文