0

Noob question ahead

So I am making a basic text-based RPG just to get me back into the basics of Python after being gone for a few months.

I'm trying to make a function that has all of the items in it as lists, and when the name of an item is called, it returns the 'stats' of the item.

E.g.

def itemlist(input):
    item1 = [name, damage, etc]
    item2 = [name, damage, etc]
    item3 = [name, damage, etc]
    ...
    return(####)

Here I want the return to pass back the item list that has the name of the item in the variable 'input', so this function will be called something like

item = itemlist(item2)

however I get an error saying that 'item2' is not defined in the main() function that I run the request in.

Am I just being an idiot or is there some solution that I'm just missing?

  • It looks like you want a dictionary, not a list. – Patrick Haugh Jan 08 '18 at 20:44
  • ... I'm not sure I understand you, but if you don't have an `item2` defined in `main` (or globally, or closed over `main`) then I'm not sure why you expect that to work. – juanpa.arrivillaga Jan 08 '18 at 20:44
  • What patrick said. Your function doesn't know that the input is supposed to be one of the items. With a dict you might not even need the function. – SuperStew Jan 08 '18 at 20:45
  • `item2` is a local name in the `itemlist()` function, nowhere else. However, you should not be using separate variables for all those lists in the first place. Use a dictionary: `itemlist = {'item1': [....], 'item2': [....]}`, and `itemlist['item2']` will get you the correct list from that. – Martijn Pieters Jan 08 '18 at 20:47

2 Answers2

1

item2 is defined inside of itemlist, not also (apparently) somewhere that your main function can see it.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

You could use a dictionary to store the items. The keys would be the item names, and the values, their respective stats.

items = {'sword': (12, 27), 'dagger': (42, 76), ...}

Then you would simply get the dictionary's values:

>>> items['sword']
(12, 27)
Right leg
  • 16,080
  • 7
  • 48
  • 81