Civerion Civerion - 1 month ago 17
Python Question

What does "x is used prior to global declaration" mean? python 2

Full code is here: http://pastebin.com/gG4JLNsX

Here's a minimal, complete, verifiable example:

import random

def newGame():
curveSetup()
printStatistics()

def curveSetup():
global curve
curve = random.randint(12,35)
global lvl
lvl = 1

def printStatistics():
global expMax
expMax = (lvl*curve)
global lvl
print "Character Level: "+str(lvl)

newGame()


Whenever I run my program, I'm getting an error saying

Warning (from warnings module):
File "D:\Code\PyRPG.py", line 64
global lvl
SyntaxWarning: name 'lvl' is used prior to global declaration


Does anyone know how to fix it? I've tried everything, I've looked around on similar questions asked on here and they are all either Python 3 or defined "x" before declaring that the variable itself is global. I've declared it is global before defining "x" therefore I don't see what is wrong with this.

EDIT: I've also defined lvl = 1 at the start, but it does not change anything at all. I've defined lvl at curveSetup() function which runs before everything else.

Answer

You're using lvl before declaring it global in printStatistics(), hence "name 'lvl' is used prior to global declaration". It is a warning only, since having global lvl anywhere in the function makes lvl global. The code still works. To get rid of the warning, move the global before use in that function:

 global lvl
 expMax = (lvl*curve)

In fact, global lvl is not required in this function at all. It is only needed if you modify the global variable. Here the value is only used in calculations without changing lvl itself.

Note that your program is horribly misusing globals. As you can see, it makes the logic difficult to follow. Global variables should be used rarely, and ideally for constants that don't change and won't require global declarations. Prefer classes to hold state instead.