Reputation: 670
Ok, so I've been looking around for around 40 minutes for how to set a global variable on Python, and all the results I got were complicated and advanced questions and more so answers. I'm trying to make a slot machine in Python, and I want to make a coins system, where you can actually earn coins so the game is better, but when I ran the code, it told me 'UnboundLocalError: local variable referenced before assignment'. I made my variable global, by putting:
global coins
coins = 50
which for some reason printed '50' and gave the UnboundLocalError error again, so from one answer I tried:
def GlobalCoins():
global coins
coins = 50
which, despite the following error, didn't print '50': 'NameError: global name 'coins' is not defined'. Soo I don't really know how to set one. This is probably extremely basic stuff and this is probably also a duplicate question, but my web searches and attempts in-program have proved fruitless, so I'm in the doldrums for now.
Upvotes: 12
Views: 45539
Reputation: 181
Omit the 'global' keyword in the declaration of coins outside the function. This article provides a good survey of globals in Python. For example, this code:
def f():
global s
print s
s = "That's clear."
print s
s = "Python is great!"
f()
print s
outputs this:
Python is great!
That's clear.
That's clear.
The 'global' keyword does not create a global variable. It is used to pull in a variable that already exists outside of its scope.
Upvotes: 15