"unboundlocalerror: Local Variable Referenced Before Assignment" When Incrementing Variable In Function
I am getting this error and I've read other posts but they say to put global before dollars = 0 which produces a syntax error because it doesn't allow the = 0. I'm using dollars as
Solution 1:
You need to add global dollars
, like follows
def search():
global dollars
print('You gain 5 bucks')
dollars = dollars + 5
shop()
Everytime you want to change a global
variable inside a function, you need to add this statement, you can just access the dollar
variable without the global
statement though,
defshop():
global dollars
shop = input("Enter something: ")
if shop == 'Shortsword':
if dollars < 4: # Were you looking for dollars?print('I\'m sorry, but you don\'t have enough dollars to buy that item.')
shop1()
if dollars > 4:
print('Item purchased!')
dollars -= someNumber # Change Number hereprint('You now have ' + dollars + ' dollars.')
You also need to reduce the dollars, when you shop for something!
P.S - I hope you're using Python 3, you'll need to use raw_input
instead.
Solution 2:
You need to put global dollars
, on a line on its own, inside any function where you change the value of dollars. In the code you've shown that is only in search()
, although I assume you'll also want to do it inside shop()
to subtract the value of the item you buy...
Post a Comment for ""unboundlocalerror: Local Variable Referenced Before Assignment" When Incrementing Variable In Function"