Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I change a global variable from inside a function?

Here's my code:

def displayInventory ():
    print ("Inventory: " + str(inventory))

def enterEcdysis():
    global xcash
    xcash -= 1
    displayInventory()

xcash = 3
inventory = [str(xcash) + ' Cash',] 
enterEcdysis()

I'm trying to make this print ['2 Cash,'], but when I run it it still comes out as 3. I'm not sure exactly what I'm doing wrong here. Shouldn't xcash -= 1 take one away from the global variable?

like image 282
jaded Jokester Avatar asked Jul 13 '26 17:07

jaded Jokester


1 Answers

It is updating xcash. The problem is inventory is out of date. You're setting it to ['3 Cash'] before the call to enterEcdysis() and you don't update it after xcash is modified.

Change your print statement to print xcash directly and you'll see it's working fine:

def displayInventory ():
    print ("Inventory: {} Cash".format(xcash))
like image 170
John Kugelman Avatar answered Jul 15 '26 05:07

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!