Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a global variable in Python

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.

like image 907
oisinvg Avatar asked Aug 30 '15 21:08

oisinvg


People also ask

How do you declare a global variable in Python?

We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.

How do you assign a value to a global variable?

If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as 'global'.

How do you define a global function in Python?

You can use global to declare a global function from within a class. The problem with doing that is you can not use it with a class scope so might as well declare it outside the class.

Is there global variable in Python?

A global variable in Python is often declared as the top of the program. In other words, variables that are declared outside of a function are known as global variables. You can access global variables in Python both inside and outside the function.


1 Answers

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.

like image 145
jamesfisk Avatar answered Oct 11 '22 10:10

jamesfisk