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

如何修复‘player变量未定义’的NameError错误?

解决NameError: name 'player' is not defined问题

问题原因

你代码里的player是main函数的局部变量,但嵌套的switchplayer函数用global player声明要使用全局变量,而全局作用域里根本没定义player,所以触发NameError。

解决方案1:改用全局变量

把player移到main函数外面,变成全局变量,这样switchplayer里的global声明就能找到它:

player = 'x'

def switchplayer():
    global player

    if player == 'x':       
          player = 'O'
    else:
          player = 'x'

def main():
    # 调用函数测试
    switchplayer()
    print(player)  # 输出O

if __name__ == "__main__":
    main()

解决方案2:用nonlocal访问外层局部变量

如果不想用全局变量,嵌套函数可以用nonlocal关键字访问外层函数(main)的局部变量,替换掉global:

def main():
    player='x'

    def switchplayer():
        nonlocal player  # 声明使用外层函数的player变量

        if player == 'x':       
              player = 'O'
        else:
              player = 'x'
    
    # 调用函数测试
    switchplayer()
    print(player)  # 输出O

if __name__ == "__main__":
    main()

两种方案的适用场景

  • 全局变量:适合需要在多个不嵌套的函数之间共享player的场景,但要注意全局变量过多会增加代码维护难度。
  • nonlocal:适合嵌套函数的场景,把变量限定在main函数作用域内,避免全局作用域污染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:57:14