Python新手编写计算器代码如何精简优化以提升运行效率?
Python计算器代码精简优化方案
核心可优化点
- 重复定义功能完全相同的
get_number1与get_number2函数,可合并为通用的数值读取函数,减少重复代码 - 两次使用
match-case匹配操作索引,可通过字典直接映射操作名、提示语、运算逻辑三者的对应关系,省去索引查询、多次匹配的冗余代码,同时避免多次调用list.index()带来的遍历开销 - 采用递归调用
main()/repeat()实现重试/重启逻辑,存在递归深度溢出风险,可替换为while循环实现更稳定 - 单独定义5个运算函数且依赖外层变量传参,可直接合并到逻辑分支中或作为字典值映射,省去冗余的函数定义,也避免了非必要的全局变量依赖
精简后可运行代码
代码功能与原代码完全一致,行数压缩超过50%,运行效率更高:
def main(): # 字典映射:操作名 -> (提示语后缀, 运算逻辑, 输出模板) op_map = { 'addition': ('add with', lambda a, b: a + b, "{} + {} =\n{}"), 'subtraction': ('subtract with', lambda a, b: a - b, "{} - {} =\n{}"), 'multiplication': ('multiply with', lambda a, b: a * b, "{} multiplied by {} =\n{}"), 'division': ('divide with', lambda a, b: a / b, "{} divided by {} =\n{}"), 'x^y': ('create an exponential with', lambda a, b: a ** b, "{} to the power of {} =\n{}") } # 通用数值读取函数 def get_num(prompt): while True: try: return float(input(prompt)) except ValueError: input('input must be a number. enter to try again.') # 读取操作类型 while True: op_input = input('What do you want to do? Addition, subtraction, multiplication, division, or x^y??\n').lower() if op_input in op_map: suffix, calc_func, output_tpl = op_map[op_input] break input('Error!, you must input one of the five options, enter to try again.') # 读取两个运算数 num1 = get_num(f"what's the first number you want to {suffix}??\n") num2 = get_num(f"what's the second number you want to {suffix}??\n") # 运算与异常处理 try: if op_input == 'x^y' and num1 == 0 and num2 == 0: raise ValueError("0^0 undefined") result = calc_func(num1, num2) print(output_tpl.format(num1, num2, result)) except ZeroDivisionError: input('Naughty naughty boy trying to divide by 0. Now you gonna have to restart the code. Press enter plz') main() except ValueError: input('Naughty boy trying 0^0, dat is undefined boi. Enter to restart the whole thing.') main() # 循环判断是否重试,替代递归避免栈溢出 while True: go_again = input('would you like to go again? Y/N\n').upper() if go_again == 'Y': main() elif go_again == 'N': exit() input('Error! You need to answer with either Y or N, enter to try again.') if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者Nato_Skato
相关产品推荐
相关产品推荐

