赋值前引用的局部变量“gamebot”

问题描述 投票:0回答:1

这是我的问题:) 我的问题很直接,第一个程序是正确的程序但第二个程序不是,为什么?

gamebot = "OFF"

def gamebot_status():
    if gamebot == "OFF":
        gamebotTest = gamebot
        print("Gamebot is right now ", gamebotTest, "\nTurning On gamebot in... \n1 \n2 \n3 \n\n", sep='')
        gamebotTest = "ON"
        print("====================\nGamebot Status = ", gamebotTest, "\n====================", sep='')
    else:
        pass
        
gamebot_status()
gamebot = "OFF"

def gamebot_status():
    if gamebot == "OFF":
        gamebotTest = "OFF"
        print("Gamebot is right now ", gamebotTest, "\nTurning On gamebot in... \n1 \n2 \n3 \n\n", sep='')
        gamebotTest = "ON"
        print("====================\nGamebot Status = ", gamebotTest, "\n====================", sep='')
    else:
        pass
        
gamebot_status()

唯一不同的是第 4 行

gamebotTest = gamebot
&
gamebotTest = "OFF"

问候

我期待这两个程序产生相同的结果。因此,请纠正我🙏

python variable-assignment local-variables
1个回答
1
投票

欢迎来到 Stackoverflow,Inferno!

为了访问最顶层作用域中的变量,您需要在函数顶部添加一个

global gamebot
(def)。

您更正后的代码将是:

gamebot = "OFF"

def gamebot_status():
    global gamebot

    if gamebot == "OFF":
        gamebotTest = "OFF"
        print("Gamebot is right now ", gamebotTest, "\nTurning On gamebot in... \n1 \n2 \n3 \n\n", sep='')
        gamebotTest = "ON"
        print("====================\nGamebot Status = ", gamebotTest, "\n====================", sep='')
    else:
        pass
        
gamebot_status()
© www.soinside.com 2019 - 2024. All rights reserved.