求助:选择选项1后Python计算器程序无法返回初始状态
Python计算器重复运算失效问题排查与修复
问题根源
- 核心逻辑无循环执行机制:输入数字、选择运算的代码仅在程序启动时执行一次,未被封装到可重复调用的结构中。选择选项1时仅调用了打印欢迎语的
main(),并未触发重新运算的流程。 - 流程控制错误:选择选项1后,程序未回到运算流程,而是继续执行后续的退出代码(
print("Thank you...")和break),直接终止程序。
修复方案
1. 重构代码结构
将完整的运算流程(数字输入、运算选择、结果计算与保存)封装为独立函数,让程序可以重复调用该函数实现多次运算。
2. 优化流程控制
用主循环控制程序整体逻辑:执行运算 → 处理用户后续选择(重新运算/读取文件/退出)。
3. 增强防御性
- 统一输入校验逻辑,减少冗余代码
- 添加文件操作的异常处理(如权限不足、写入失败)
- 完善所有非法输入的错误提示
修复后的完整代码
import math def print_welcome(): print("*****Welcome*****") print("Please enter two numbers and the operation you want to perform : \n") def get_valid_number(prompt): while True: try: return float(input(prompt)) except ValueError: print("Oops! That was no valid number. Try again...") def get_valid_operation(): while True: operation = input("> Enter operation (+, -, *, /): ") if operation in ('+', '-', '*', '/'): return operation else: print("Oops! Operation must be +, -, * or / Try again...") def perform_calculation(): num1 = get_valid_number("> Enter first number : ") num2 = get_valid_number("> Enter second number : ") operation = get_valid_operation() try: if operation == '+': result = num1 + num2 elif operation == '-': result = num1 - num2 elif operation == '*': result = num1 * num2 elif operation == '/': if num2 == 0: raise ZeroDivisionError result = num1 / num2 # 保存结果到文件,添加异常处理 try: with open("test.txt", "a") as f: log_line = f"{num1} {operation} {num2} = {result}\n" f.write(log_line) print(log_line.strip()) print("Input and result saved to file.") except IOError: print("Failed to save result to file.") except ZeroDivisionError: print("Invalid input: division by zero") return False # 运算失败,返回False return True def read_file(): while True: try: file_name = input("Enter file name: ").lower() with open(file_name, "r") as f: print(f.read()) break except FileNotFoundError: print("File not found. Try again...") except IOError: print("Failed to read file. Check permissions and try again...") def main(): print_welcome() while True: # 执行一次运算 perform_calculation() # 后续选项选择 print("\nNow you have two options: ") print("1. Perform another operation") print("2. Read equations from a file") print("3. Exit") while True: try: choice = int(input("Enter your choice: ")) if choice in (1, 2, 3): break else: print("Invalid input. Choose 1, 2 or 3...") except ValueError: print("Invalid input. Enter a number...") if choice == 1: continue # 回到主循环,重新执行运算 elif choice == 2: read_file() elif choice == 3: print("Thank you for using this calculator. Goodbye!") break if __name__ == "__main__": main()
关键优化点
- 将输入校验、运算执行、文件读取拆分为独立函数,代码更模块化、易维护
- 主循环控制程序生命周期,选择1时直接回到运算流程
- 添加了文件读写的IO异常处理,增强程序防御性
- 优化了输入提示的清晰度,减少用户困惑
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

