Problem with global variables

python

#1

I'm creating my own roll and move game called Dungeon Quest (actually I originally wrote it back in college but lost it) and I'm having an issue calling a list in one function but not in another and I don't understand why. This is only a small section of it.

Here's my inventory.py source: http://hastebin.com/uzeqelomeq.py

if I call list_inventory() it allows me to print out elements from the list.

Here's my Actions.py source: http://hastebin.com/rarivojoxu.py

If I import Inventory and call find_gold() it crashes with this:

  File "/home/bran/dungeon-quest/actions.py", line 65, in find_gold
    print inv
NameError: global name 'inv' is not defined

I'm doing the exact same thing so why doesn't it work?


#2

@brando56894,
If have read this
http://stackoverflow.com/questions/15959534/python-visibility-of-global-variables-in-imported-modules
you will probably start using

inventory.inv[2]

#3

Cool thanks! I didn't know that they were only global to the module. Last time I did this (about 4-5 years ago) I was using global variables, but within the same module so I never ran into this issue.


#4

@brando56894
I do not know why you are using a list instead of using a dictionary

inv = {
 health: 0,
 gold: 0,
 other: 0
}

then accessing with

 inventory.inv["gold"]

#5

I had originally done it with dictionaries but couldn't figure out how to change the values of the keys, probably because I was trying to access them incorrectly. All the answers I found for changing a value in a dictionary were complex and required recreating the dictionary each time you wanted to change a value.

I tried simple things like inv["gold"] += amount_of_gold_found and it kept throwing errors.

After about 2 hours of messing with it, I decided to use a list since it was easier for me to figure out by myself.