How to set a global variable in Python -
ok, i've been looking around around 40 minutes how set global variable on python, , results got complicated , advanced questions , more answers. i'm trying make slot machine in python, , want make coins system, can earn coins game better, when ran code, told me 'unboundlocalerror: local variable referenced before assignment'. made variable global, putting:
global coins coins = 50
which reason printed '50' , gave unboundlocalerror error again, 1 answer tried:
def globalcoins(): global coins coins = 50
which, despite following error, didn't print '50': 'nameerror: global name 'coins' not defined'. soo don't know how set one. extremely basic stuff , duplicate question, web searches , attempts in-program have proved fruitless, i'm in doldrums now.
omit 'global' keyword in declaration of coins outside function. this article provides survey of globals in python. example, code:
def f(): global s print s s = "that's clear." print s s = "python great!" f() print s
outputs this:
python great! that's clear. that's clear.
the 'global' keyword not create global variable. used pull in variable exists outside of scope.
Comments
Post a Comment