12

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.

3
  • Did you put both those pieces of code in the same file? Your code doesn't print anything, so why do you expect it to product any output? Commented Aug 30, 2015 at 21:53
  • You need to declare coins and then when you want to change it declare it global. Commented Aug 30, 2015 at 21:59
  • Thank you so much, this finally works now. thanks! Commented Aug 30, 2015 at 22:04

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It's true that global itself doesn't create the variable, but it doesn't require that it already exist either. Inside a function, you can do global x and then x = 10 and that will create the global variable if it doesn't already exist.
This answer is incorrect. As @BrenBarn says, you can create a global variable. The reason why the last output is not "Python is great!" is because the global variable inside the function, s, has already been assigned a new value "That's clear."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.