How do I add quantities of items in an inventory?

I use inventory.append(“{Item Name}” to add items in my text based adventure game, however I am trying to make a gold function. How do I add quantities of items to my inventory that can be added and subtracted? I could write inventory.append(“5 Gold”) but I wouldn’t be able to modify only the number. Thank you for helping.

@IanJones17 You could try using dictionaries. Instead of having a list with each item, you have each item as a key, and the value as the amount. Like this:

inventory = {}
inventory["gold"] = 5

# to add more gold
inventory["gold"] += 2

# get the value
print(inventory["gold"])
2 Likes

You could use a dataclass instead of strings:

from dataclasses import dataclass

@dataclass
class Item:
   amount: int
   name: str

inventory.append(Item(5, "gold"))
1 Like

Thank you so much. That was really helpful

Thank you so much. That was great!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.