Python计算器迭代逻辑修复与指定指令实现问询
Python计算器代码优化(保留原结构)
核心修改说明
- 移除冗余的重复操作选择循环,整合主逻辑到一个循环中
- 修复
select_op的递归调用问题,改用循环内部处理避免栈溢出 - 调整操作数与操作符的获取时机,确保每次计算后可重新输入
- 修正除法逻辑的判断顺序,先检查除数是否为0再执行计算
- 实现
$结尾重新询问操作、#结尾终止程序的功能
优化后完整代码
# ------------------------------------- # TODO: Write the select_op(choice) function here # This function should cover Task 1 (Section 2) and Task 3 def select_op(): while True: choice = input("Enter choice(+,-,*,/,^,%,#,$): ") # 处理以$结尾的情况:重新询问操作 if choice.endswith("$"): print("Reset operation selection...") continue # 处理以#结尾的情况:终止程序 elif choice.endswith("#"): print("Done. Terminating") exit() # 处理无效操作 elif choice not in ("+", "-", "*", "/", "^", "%"): print("Unrecognized operation") continue else: return choice def select_operand(): try: first_operand = float(input("Enter the first number: ")) return first_operand except ValueError: print("Not a valid number. Please enter again.") return select_operand() def select_operand_2(): try: second_operand = float(input("Enter the second number: ")) return second_operand except ValueError: print("Not a valid number. Please enter again.") return select_operand_2() def operation(choice, first_operand, second_operand): if choice == "+": print(f"Result: {first_operand + second_operand}") elif choice == "-": print(f"Result: {first_operand - second_operand}") elif choice == "*": print(f"Result: {first_operand * second_operand}") elif choice == "/": if second_operand == 0: print("Division by zero is not allowed") else: print(f"Result: {first_operand / second_operand}") elif choice == "^": print(f"Result: {first_operand ** second_operand}") elif choice == "%": print(f"Result: {first_operand % second_operand}") # 主循环:实现重复计算功能 while True: print("\nSelect operation.") print("1.Add : + ") print("2.Subtract : - ") print("3.Multiply : * ") print("4.Divide : / ") print("5.Power : ^ ") print("6.Remainder: % ") print("7.Terminate: # ") print("8.Reset : $ ") # 获取操作选择 choice = select_op() # 获取操作数 first_num = select_operand() second_num = select_operand_2() # 执行计算 operation(choice, first_num, second_num)
关键修改细节
select_op函数优化:- 移除递归调用,改用
continue重新发起询问,避免栈溢出 - 调整判断顺序,优先处理
$和#的结尾情况 - 无效操作时用
continue重新循环,而非递归
- 移除递归调用,改用
主逻辑整合:
- 将操作选择、操作数获取、计算逻辑放入同一个
while True循环,实现重复执行 - 每次循环重新打印操作菜单,符合重复计算的交互流程
- 将操作选择、操作数获取、计算逻辑放入同一个
除法逻辑修复:
- 先判断除数是否为0,再执行除法计算,避免错误输出
交互体验优化:
- 计算结果添加
Result:前缀,输出更清晰 - 操作选择前添加换行,界面更整洁
- 计算结果添加
内容的提问来源于stack exchange,提问作者Niki Jr
相关产品推荐
相关产品推荐

