Python计算器实现用户返回首页后重启代码的方法及优化建议
Python计算器功能实现与代码优化方案
一、核心功能实现修正
当前代码存在以下问题:
- 用户输入
n时无法回到首页重新选择操作 - 继续操作的循环逻辑错误(例如选择减法后输入
y却调用加法函数) - 多个独立
while循环无法实现流程闭环控制
修正方案
用主循环包裹整个程序流程,每次完成计算后询问用户,根据输入决定继续当前操作或回到首页重新选择,核心逻辑如下:
def main(): while True: # 首页选择操作 ask = startup() # 基础运算分支 if ask == "1": while True: add() choice = input("Do you want to continue (y) or go back to home (n): ").lower() if choice == "n": break # 回到首页重新选择 elif choice != "y": print("Invalid input, returning to home.") break # 减法、乘法等其他基础运算分支逻辑同上 elif ask == "2": while True: subtract() choice = input("Do you want to continue (y) or go back to home (n): ").lower() if choice == "n": break # 复杂运算分支 elif ask == "5": ask2 = input("Do you want to do 1. square root, 2. cube root, or 3. exponent? (1/2/3): ").strip() if ask2 == "1": while True: square_root() choice = input("Do you want to continue (y) or go back to home (n): ").lower() if choice == "n": break else: print("Invalid choice, please try again.")
二、代码优化建议
1. 移除无用依赖
当前导入的random和time未被使用,直接删除:
import math import numpy as np
2. 避免全局变量
将startup函数改为返回用户选择的操作,而非修改全局变量:
def startup(): print("Welcome to this math python program") return input( "Do you want to solve 1. add, 2. subtract, 3. multiply, 4. divide, or 5. other complex problems? (answer with 1,2,3,4,5): " ).strip()
3. 用字典映射操作,减少冗余分支
把操作选项与对应函数关联,替代大量if-elif或独立while循环:
basic_ops = { "1": add, "2": subtract, "3": multiply, "4": divide } complex_ops = { "1": square_root, "2": cube_root, "3": exponent }
主循环中可简化为:
ask = startup() if ask in basic_ops: op_func = basic_ops[ask] while True: op_func() if ask_continue() == "n": break
4. 添加输入错误处理
用户输入非数字时会抛出异常,封装通用数字输入函数:
def get_number(prompt): while True: try: return float(input(prompt)) except ValueError: print("Please enter a valid number.")
计算函数中直接调用:
def add(): print("Addition") num1 = get_number("First number: ") num2 = get_number("Second Number: ") print(f"The answer is {num1 + num2}")
5. 遵循PEP8命名规范
函数名改为下划线分隔的小写格式,例如squareRoot → square_root,提升代码可读性。
6. 合并重复询问逻辑
封装询问用户是否继续的通用函数:
def ask_continue(): while True: choice = input("Do you want to continue (y) or go back to home (n): ").lower().strip() if choice in ["y", "n"]: return choice print("Invalid input, please enter 'y' or 'n'.")
7. 用f-string优化输出格式
替代字符串拼接,让代码更简洁:
# 原写法 print("The answer is " + str(num)) # 优化后 print(f"The answer is {num}")
完整优化后代码示例
import math import numpy as np def get_number(prompt): while True: try: return float(input(prompt)) except ValueError: print("Please enter a valid number.") def ask_continue(): while True: choice = input("Do you want to continue (y) or go back to home (n): ").lower().strip() if choice in ["y", "n"]: return choice print("Invalid input, please enter 'y' or 'n'.") def startup(): print("\nWelcome to this math python program") return input( "Choose an operation: 1. Add, 2. Subtract, 3. Multiply, 4. Divide, 5. Complex Operations (1/2/3/4/5): " ).strip() def add(): print("\n=== Addition ===") num1 = get_number("First number: ") num2 = get_number("Second number: ") print(f"The answer is {num1 + num2}") def subtract(): print("\n=== Subtraction ===") num1 = get_number("First number: ") num2 = get_number("Second number: ") print(f"The answer is {num1 - num2}") def multiply(): print("\n=== Multiplication ===") num1 = get_number("First number: ") num2 = get_number("Second number: ") print(f"The answer is {num1 * num2}") def divide(): print("\n=== Division ===") while True: num1 = get_number("First number: ") num2 = get_number("Second number: ") if num2 != 0: break print("Cannot divide by zero, please enter a non-zero second number.") print(f"The answer is {num1 / num2}") def square_root(): print("\n=== Square Root ===") num = get_number("Enter the number to find square root of: ") if num < 0: print("Square root of negative number is not real.") return print(f"The square root of {num} is {math.sqrt(num)}") def cube_root(): print("\n=== Cube Root ===") num = get_number("Enter the number to find cube root of: ") print(f"The cube root of {num} is {np.cbrt(num)}") def exponent(): print("\n=== Exponents ===") base = get_number("Enter the base number: ") power = get_number("Enter the exponent: ") print(f"{base} to the power of {power} is {base ** power}") def main(): basic_ops = {"1": add, "2": subtract, "3": multiply, "4": divide} complex_ops = {"1": square_root, "2": cube_root, "3": exponent} while True: choice = startup() if choice in basic_ops: op_func = basic_ops[choice] while True: op_func() if ask_continue() == "n": break elif choice == "5": complex_choice = input("\nChoose complex operation: 1. Square Root, 2. Cube Root, 3. Exponents (1/2/3): ").strip() if complex_choice in complex_ops: op_func = complex_ops[complex_choice] while True: op_func() if ask_continue() == "n": break else: print("Invalid choice, returning to home.") else: print("Invalid choice, please try again.") if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者Abhay Kapatkar
相关产品推荐
相关产品推荐

