2

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
Ben
  • 23
  • 3

3 Answers3

3

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.

E.g.

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(edited)
    global Credit
    Credit = Credit - 0.20
Community
  • 1
  • 1
ledwinder96
  • 241
  • 5
  • 13
1

Anytime you want to write to a global variable in another function in python, you should let python know you want to use the global variable. Before the first line of main insert:

global Credit
1

You don't declared your variable . A variable that declared outside the function don't work into function . To use that variable you have to make the credit in this case as global variable. And then everything may become fine . All the best .

x = something #declearing a local variable
def something():
    global x # setting local x variable as global variable, so x can be use into as well as outside of the function
    print x
    #or do something u like .
Tanzir Uddin
  • 51
  • 1
  • 9