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

Python算术计算器函数无法返回计算结果?求排查解决

问题分析与解决

你的计算器函数逻辑本身是正常的,调用calculator("-", 5, 3)确实会返回2,但你没有输出这个返回值,所以控制台看不到结果。

解决方法

直接调用函数时,Python不会自动打印返回值,你需要用print()把结果输出:

def calculator(a,b,c):
    # 别用sum当变量名,它是Python内置函数
    result = 0
    if a == "-":
        result = b - c
    elif a == "+":
        result = b + c
    elif a == "*":
        result = b * c
    elif a == "/":
        result = b / c
    return result

# 用print输出结果
print(calculator("-", 5, 3))  # 会打印出2

额外优化建议

  • 替换sum变量名:sum是Python内置的求和函数,用它当变量名会覆盖原功能,换成result这类名称更安全
  • 增加错误处理:如果传入了不支持的运算符(比如%),当前函数会返回0,容易造成误解,可以加else分支处理:
def calculator(a,b,c):
    result = None
    if a == "-":
        result = b - c
    elif a == "+":
        result = b + c
    elif a == "*":
        result = b * c
    elif a == "/":
        # 补充除数为0的判断
        if c == 0:
            return "错误:除数不能为0"
        result = b / c
    else:
        return f"错误:不支持的运算符{a}"
    return result

print(calculator("%", 5, 3))  # 会打印错误提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:35:22