这个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
相关产品推荐
相关产品推荐

