You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化Python计算器代码,使其更紧凑易读?

Python计算器代码优化方案

可以通过操作映射字典消除重复的分支逻辑,把运算逻辑和输入处理分离,让代码更紧凑易读,同时还能增强输入合法性的处理:

def calculator():
    # 用字典映射操作到对应的计算逻辑
    ops = {
        'add': lambda a, b: a + b,
        'sub': lambda a, b: a - b,
        'mul': lambda a, b: a * b,
        'div': lambda a, b: a / b if b != 0 else None
    }
    
    while True:
        op = input("Enter 'add', 'sub', 'mul' or 'div': ").strip()
        # 检查操作是否合法
        if op not in ops:
            print("Invalid operation. Please try again.")
            continue
        
        # 统一处理数字输入,捕获非数字的异常
        try:
            first = float(input("First number: "))
            second = float(input("Second number: "))
        except ValueError:
            print("Invalid number. Please enter numeric values.")
            continue
        
        # 执行计算
        result = ops[op](first, second)
        # 处理除法零的情况
        if result is None:
            print("Cannot divide by zero. Please try again.")
        else:
            print(f"Result: {result}")
            break

if __name__ == "__main__":
    calculator()

优化关键点

  • 消除重复代码:把原本分散在各个if-elif里的输入、计算逻辑抽出来统一处理,避免冗余
  • 逻辑集中管理:用字典ops统一管理所有运算,后续新增操作只需往字典里加键值对,不用修改分支结构
  • 增强健壮性:增加了非数字输入的异常处理,比原代码更严谨
  • 可读性提升:每个模块的职责清晰,从操作选择、输入处理到计算执行,流程一目了然

内容的提问来源于stack exchange,提问作者EURepublican

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 18:53:29