python随机出 5 道两个整数(能够随机进行加、减法、乘、除)的题,统计正确答题数和用时,(除法要求得到结果为整除数,结果四舍五入取整,输入负值不会中途退出,并加入异常处理,输入不正确的数据类型 不会导致程序中止),参考例 3.15 和例 3.18.
时间: 2024-10-26 10:16:57 浏览: 21
在Python中,你可以使用`random`模块生成题目,`time`模块计算时间,`try-except`结构进行异常处理。这里是一个示例程序,它会随机生成加减乘除的题目,用户输入答案并计分,同时处理除法的整除需求和错误输入:
```python
import random
import time
def generate_question():
operator = random.choice(["+", "-", "*", "/"])
if operator == "/":
divisor = random.randint(1, 10) # 防止除以0
dividend = divisor * random.choice([-1, 1]) # 确保有正负两种情况
else:
dividend = random.randint(-100, 100)
divisor = 1 # 因为加减不需要特殊处理
question = f"{dividend} {operator} ?"
return question, dividend, operator
def calculate_answer(dividend, operator):
if operator == "+":
answer = sum([dividend])
elif operator == "-":
answer = abs(dividend)
elif operator == "*":
answer = dividend * 1
else:
# 判断是否能整除
answer = int(dividend / divisor)
return answer
def main():
correct_answers = 0
start_time = time.time()
while True:
try:
question, dividend, _ = generate_question()
print(question)
user_input = input("请输入答案: ")
# 输入检查
if not isinstance(user_input, int):
raise ValueError("输入的数据类型错误,请输入整数.")
answer = calculate_answer(dividend, _)
if user_input == str(answer):
correct_answers += 1
print(f"回答正确! 正确答案是{answer}.")
else:
print(f"回答错误! 正确答案是{answer}.")
except ValueError as ve:
print(ve)
except ZeroDivisionError:
print("除数不能为零,请重新输入.")
except Exception as e:
print("发生了未知错误:", e)
# 结束条件:用户输入非数字或选择退出
if "exit" in user_input.lower() or not user_input.isdigit():
break
elapsed_time = time.time() - start_time
print(f"总共答题{correct_answers}道,用时大约{elapsed_time:.2f}秒.")
if __name__ == "__main__":
main()
```
阅读全文