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

如何编写含2层嵌套函数、支持任意数字加减的Python calculator函数

原代码错误点
  • 未定义核心变量:代码中使用的result、operators、digits、i、j均没有提前声明,运行直接触发变量未定义报错
  • 返回逻辑完全不符合链式调用要求:calculator接收数字后应该返回operation函数接收运算符,operation接收非=的运算符后应该返回calculation函数接收下一个数字,但原代码中operation直接返回运算符字符串、calculator最后递归调用自身,完全无法支持连续括号调用的写法
  • 终止逻辑错误:遇到=时需要直接返回累计结果,不需要写while循环处理多组数据,链式调用每一步只会处理单个参数
  • 没有用闭包保存中间状态:要实现无全局变量的连续运算,必须通过闭包存储当前的累计计算结果,原代码没有相关逻辑
正确实现代码
def calculator(x: int):
    # 闭包存储当前累计结果
    total = x
    def operation(operator: str):
        # 遇到结束标识直接返回累计结果
        if operator == "=":
            return total
        def calculation(y: int):
            nonlocal total
            # 根据运算符更新累计结果
            if operator == "+":
                total += y
            elif operator == "-":
                total -= y
            # 处理完数字后返回operation,接收下一个运算符
            return operation
        return calculation
    # 接收第一个数字后返回operation,等待接收运算符
    return operation
调用验证

执行calculator(1)('+')(4)('-')(2)('=')即可得到返回结果3,完全满足要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:54:01