Python计算器try/except与while循环问题:零除流程异常及重循环失效
修复计算器的零除处理与重新计算功能
修改后的完整代码
while True: # 输入数字与运算符,处理非法输入和零除前置检查 while True: try: num1 = float(input("Please enter a number:")) num2 = float(input("Please enter another number: ")) operator = input("Please enter the operator (+, -, *, /): ") # 提前检查除法零除情况,引导重新输入第二个数 if operator == "/" and num2 == 0: print("You cannot divide by zero. Please enter a non-zero number for the second value!") continue break except ValueError: print("Wrong key entered. Please key in a number") # 执行计算逻辑 if operator == "+": calculation = num1 + num2 print(f"{num1} + {num2} = {calculation}") elif operator == "-": calculation = num1 - num2 print(f"{num1} - {num2} = {calculation}") elif operator == "*": calculation = num1 * num2 print(f"{num1} * {num2} = {calculation}") elif operator == "/": calculation = num1 / num2 print(f"{num1} / {num2} = {calculation}") else: print("You have not entered a valid operator, please try again.") continue # 询问是否启动新计算,处理非法选择输入 while True: choice = input("Continue - Y / No - N: ").strip().upper() if choice in ["Y", "N"]: break print("Invalid choice, please enter Y or N.") if choice == "N": print("Exiting calculator.") break
关键修改说明
解决零除后重新输入数字的问题:
在数字输入的循环中增加前置检查,当用户选择除法且第二个数为0时,直接提示并引导重新输入第二个数字,而非跳转到运算符输入环节。实现新计算的重循环功能:
将整个计算流程(数字输入、运算符输入、计算、结果输出)包裹在最外层的while True循环中。每次计算完成后,通过选择判断是否重新执行完整流程,或退出程序。额外优化:
- 使用f-string简化结果输出的字符串拼接;
- 增加用户选择的合法性校验,避免无效输入导致的流程异常;
- 优化运算符非法输入的处理逻辑,确保用户能重新发起有效计算。
内容的提问来源于stack exchange,提问作者Youzohka
相关产品推荐
相关产品推荐

