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

Python变量赋值前引用问题:函数更新全局变量失败求解

问题解决方案

代码中的两个核心问题

  • 比较运算符误用:原代码里的<<是位左移运算符,不是小于比较,应该改成<
  • 全局变量修改未声明:函数内要修改全局变量indexer,必须先通过global关键字声明,否则Python会将其视为局部变量,触发UnboundLocalError

修正后的代码(使用global关键字)

indexer = 0
my_list = ["no", "yes"]  # 避免用list作为变量名,会覆盖Python内置的list类型
maybe = 1

def test():
    global indexer  # 声明要操作的是全局作用域的indexer
    if indexer < maybe:
        indexer = maybe
        print("boooo")

test()
print(indexer)  # 输出1,验证全局变量已被修改

替代方案(无需global,更推荐)

如果不想依赖全局变量,可以通过函数返回值的方式更新变量,这种方式更符合代码封装原则,减少副作用:

indexer = 0
my_list = ["no", "yes"]
maybe = 1

def test(current_index, new_index):
    if current_index < new_index:
        print("boooo")
        return new_index
    return current_index

# 通过函数返回值更新indexer
indexer = test(indexer, maybe)
print(indexer)  # 输出1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:45:53