简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM