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

Python多if分支计算函数仅首个分支生效,返回错误结果求修正

问题原因
  • 变量赋值逻辑错误:你给出的参数示例中使用了比较运算符==而非赋值运算符=,没有实际给direction和number设置你期望的'B'、2值,导致分支判断时匹配失败。同时字符串值B需要包裹引号,否则会被识别为未定义的变量报错。
  • 函数设计不合理:当前函数直接依赖全局变量做判断,很容易因为变量作用域问题、值被意外篡改导致逻辑异常,建议将判断变量作为参数传入函数。
修正后完整代码
# 正确为变量赋值
direction = 'B'
number = 2 

# 改造函数接收参数,消除全局变量依赖
def price_cal(direction, number):
    if direction == 'A' and number == 1:
        return 1
    elif direction == 'A' and 1 < number <= 9:
        return 2
    elif direction == 'A' and 9 < number <= 13:
        return 3
    elif direction == 'B' and number == 1:
        return 4 
    elif direction == 'B' and 1 < number <= 9:
        return 5
    else:
        return 6

# 调用函数时传入对应参数
print(price_cal(direction, number))
运行结果

上述代码运行后输出5,和你预期的返回值一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 18:15:04