Local variable 'gamebot' referenced before assignment
Question:
This is my question here:)
My question is straight forward, the first program is the correct program but second program isnt, why ?
gamebot = "OFF"
def gamebot_status():
if gamebot == "OFF":
gamebotTest = gamebot
print("Gamebot is right now ", gamebotTest, "nTurning On gamebot in... n1 n2 n3 nn", 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 nn", sep='')
gamebotTest = "ON"
print("====================nGamebot Status = ", gamebotTest, "n====================", sep='')
else:
pass
gamebot_status()
the only diference is in Line 4
gamebotTest = gamebot
& gamebotTest = "OFF"
REGARDS
I was expecting both programs to yield same results. Thus, correct me pls
Answers:
In order to access the variable in the topmost scope, you need to add a global gamebot
to the top of the function (def).
Your corrected code would then be:
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 nn", sep='')
gamebotTest = "ON"
print("====================nGamebot Status = ", gamebotTest, "n====================", sep='')
else:
pass
gamebot_status()
This is my question here:)
My question is straight forward, the first program is the correct program but second program isnt, why ?
gamebot = "OFF"
def gamebot_status():
if gamebot == "OFF":
gamebotTest = gamebot
print("Gamebot is right now ", gamebotTest, "nTurning On gamebot in... n1 n2 n3 nn", 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 nn", sep='')
gamebotTest = "ON"
print("====================nGamebot Status = ", gamebotTest, "n====================", sep='')
else:
pass
gamebot_status()
the only diference is in Line 4
gamebotTest = gamebot
& gamebotTest = "OFF"
REGARDS
I was expecting both programs to yield same results. Thus, correct me pls
In order to access the variable in the topmost scope, you need to add a global gamebot
to the top of the function (def).
Your corrected code would then be:
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 nn", sep='')
gamebotTest = "ON"
print("====================nGamebot Status = ", gamebotTest, "n====================", sep='')
else:
pass
gamebot_status()