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

这个Python 3.8函数中deathmax变量未正常更新是什么原因?

错误根源
  • 赋值语法错误:代码中deathmax == v['death']是布尔判断语句,仅用于比对两个值是否相等,不会完成赋值操作,正确赋值需要使用单个等号=。
  • 变量作用域问题:deathmax是定义在函数外部的全局变量,若要在函数内部修改其值,必须提前使用global deathmax声明变量使用全局作用域实例,否则Python会将其识别为未定义的局部变量,直接调用修改会触发异常。
修正后代码
ans = {'Cuba I': {'Month': 'October', 'Year': 1924, 'Max Sustained Winds': 165, 'Areas Affected': ['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], 'Damage': 'Damages not recorded', 'death': 90}, 'San Felipe II Okeechobee': {'Month': 'September', 'Year': 1928, 'Max Sustained Winds': 160, 'Areas Affected': ['Lesser Antilles', 'The Bahamas', 'United States East Coast', 'Atlantic Canada'], 'Damage': 100000000.0, 'death': 4000}}

deathmax = 0
def maxdeaths(ans):
    # 声明使用全局变量
    global deathmax
    for k,v in ans.items():
        if v['death'] >= deathmax:
            print(type(v['death']))
            # 改为赋值运算符
            deathmax = v['death']
    return deathmax

print(maxdeaths(ans))

运行上述代码输出结果为4000,符合预期。

更优实现方案

推荐避免使用全局变量,直接在函数内部初始化最大值变量,降低作用域冲突风险:

ans = {'Cuba I': {'Month': 'October', 'Year': 1924, 'Max Sustained Winds': 165, 'Areas Affected': ['Central America', 'Mexico', 'Cuba', 'Florida', 'The Bahamas'], 'Damage': 'Damages not recorded', 'death': 90}, 'San Felipe II Okeechobee': {'Month': 'September', 'Year': 1928, 'Max Sustained Winds': 160, 'Areas Affected': ['Lesser Antilles', 'The Bahamas', 'United States East Coast', 'Atlantic Canada'], 'Damage': 100000000.0, 'death': 4000}}

def maxdeaths(ans):
    deathmax = 0
    for k,v in ans.items():
        if v['death'] >= deathmax:
            deathmax = v['death']
    return deathmax

print(maxdeaths(ans))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:24:03