Ben Ben - 8 months ago 39
Python Question

Need help fixing a game I made in Python

I have been set a task to make a fruit machine game in python, however I am facing a small problem, it involves a variable. it is saying that I have referenced the variable before it's assignment, even though I have assigned it. It seems to be reading it as a local variable instead of a global variable. How do i fix this.

This is the part causing the most trouble

Credit = 1

def main(): #the main program
Credit = Credit - 0.20
print("Credit remaining = " + Credit) #tells the player the amount of credit remaining
print("\n *** The Wheel Spins... *** \n") #Spinning the wheel
print(input("\n (press enter to continue) \n"))

error message

line 19, in main
Credit = Credit - 0.20
UnboundLocalError: local variable 'Credit' referenced before assignment


The answer to this question might help you (copy-pasted below).

If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword.


global someVar
someVar = 55

This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.

The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.

You both read and change the value of Credit you need to rewrite your code into something along the lines of:

def main(): #the main program
global Credit
Credit = Credit - 0.20