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

Python:如何在函数中调用另一个函数处理变量以得到正确求和结果?

解决no_teen_sum函数的逻辑问题

哦,我知道你哪里踩坑了!你写的fix_teen函数逻辑是对的,但在no_teen_sum里调用它时,没把函数返回的修正值赋值给原变量。Python里整数是不可变类型,函数内部修改n的操作不会影响外部的a、b、c,所以相当于白调用了这个函数,最后还是用原始数值求和了。

修正后的代码

只需要把每个变量替换成fix_teen的返回结果就行:

def no_teen_sum(a, b, c):
    # 将每个变量替换为修正后的值
    fixed_a = fix_teen(a)
    fixed_b = fix_teen(b)
    fixed_c = fix_teen(c)
    return fixed_a + fixed_b + fixed_c

def fix_teen(n):
    # 把条件写得更简洁,逻辑保持不变
    if n in {13, 14} or 17 <= n <= 19:
        return 0
    return n

print(no_teen_sum(1, 2, 13))  # 输出3,符合预期

更简洁的写法(可选)

如果想少写几行代码,也可以直接在求和时调用fix_teen:

def no_teen_sum(a, b, c):
    return fix_teen(a) + fix_teen(b) + fix_teen(c)

def fix_teen(n):
    return 0 if n in {13,14} or 17 <= n <= 19 else n

这样运行no_teen_sum(1,2,13)就会返回1+2+0=3,完全符合你的需求啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:07:26