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

如何用函数替换Python计算器代码中的重复if语句?

优化后的简易计算器代码

以下是遵循编码规范、消除重复代码后的优化版本,核心改进包括封装重复逻辑为可复用函数、用字典替代冗长的条件分支等:

关键优化点

  • 封装输入处理与验证逻辑到通用函数,避免重复编写循环和重启检查
  • 用字典映射运算符与计算函数,替代冗长的if-elif分支
  • 拆分不同类型输入的验证规则,代码更易维护
  • 修复原代码中未初始化变量等潜在问题

完整优化代码

def get_user_input(prompt):
    """基础输入处理,处理重启($)和退出(#)指令"""
    while True:
        user_input = input(prompt).strip()
        print(user_input)
        if user_input.endswith('$'):
            return ('restart',)
        elif user_input.endswith('#'):
            exit()
        else:
            return ('valid', user_input)

def get_validated_input(prompt, validator):
    """通用验证函数,结合基础输入处理与自定义验证规则"""
    while True:
        result = get_user_input(prompt)
        if result[0] == 'restart':
            return ('restart',)
        input_str = result[1]
        is_valid, value_or_error = validator(input_str)
        if is_valid:
            return ('valid', value_or_error)
        print(value_or_error)

def validate_operator(input_str):
    """验证运算符是否合法"""
    valid_ops = {'+', '-', '*', '/', '^', '%'}
    if input_str in valid_ops:
        return (True, input_str)
    return (False, "Unrecognised operation")

def validate_number(input_str):
    """验证输入是否为有效数字"""
    try:
        return (True, float(input_str))
    except ValueError:
        return (False, "Unidentified operand")

def validate_proceed(input_str):
    """验证继续/退出选择"""
    input_upper = input_str.upper()
    if input_upper == 'Y':
        return (True, 'continue')
    elif input_upper == 'N':
        exit()
    elif input_upper.endswith('$'):
        return (True, 'restart')
    return (False, "Unrecognised answer")

# 运算符与计算逻辑的映射字典
operations = {
    '+': lambda a, b: a + b,
    '-': lambda a, b: a - b,
    '*': lambda a, b: a * b,
    '/': lambda a, b: a / b,
    '^': lambda a, b: a ** b,
    '%': lambda a, b: a % b
}

# 主循环
while True:
    print("Select 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    : $ ")

    # 获取合法运算符
    result = get_validated_input("Enter choice (+, -, *, /, ^, %, #, $): ", validate_operator)
    if result[0] == 'restart':
        continue
    choice = result[1]

    # 获取第一个操作数
    result = get_validated_input('First number: ', validate_number)
    if result[0] == 'restart':
        continue
    first_operand = result[1]

    # 获取第二个操作数
    result = get_validated_input('Second number: ', validate_number)
    if result[0] == 'restart':
        continue
    second_operand = result[1]

    # 执行计算并输出结果
    try:
        calculation_result = operations[choice](first_operand, second_operand)
        print(calculation_result)
    except ZeroDivisionError:
        print("Can't divide by zero")

    # 询问是否继续计算
    proceed_result = get_validated_input('Want to perform another calculation(Y/N): ', validate_proceed)
    if proceed_result[1] == 'restart':
        continue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 16:06:03