Home > database >  Python - after adding some items the list is still empty problem
Python - after adding some items the list is still empty problem

Time:10-11

I'm new to programming, so please explain me one thing I have got a character. He has got a inventory. The inventory is a list

class Steve:
    def __init__(self):
        self.inv = []

I'm trying to do a picking-up mechanic. If there wasn't such a item before, I will add it to the inventory. But if there already was the "new item", i want there to be an amount counter right in the list like:

    def pickUp(self, item):
        amount = 0
        for i in self.inv:
            if i == item:
                amount  = 1
                self.inv[i] == self.inv[i]   amount
            else:
                self.inv.append(item)

But if I try it:

s = Steve()

s.pickUp('wood')
s.pickUp('wood')
s.pickUp('dirt')
print(s.inv)

I will see that the list is empty. What is the mistake and why?

Sorry for my bad english im Slavic

CodePudding user response:

Because "self. inv" is empty in the class definition, the program does not execute the for loop statement. You can preset a value for the "self. inv" list. There is an error in the line

self. inv [i]==self. inv [i] amount

If the str type is passed in, it cannot be added.

CodePudding user response:

You for loop won't behave as expected, it will most of the times end up in the else case, appending the same item multiple times.

In your case, I'd ask in the pick_up() method:

# use snake case naming convention
def pick_up(self, item):
    amount = 0
    if item in self.inv:
        amount  =1
    else:
        self.inv.append(item)

however, this leaves you with amount being 0 on each new call to pick_up().

So in your case, I suggest to make self.inv a dictionary, then:

def pick_up(self, item):
    if item in self.inv.keys():
        self.inv[item]  = 1
    else:
        self.inv[item] = 0

if you make it a defaultdict self.inv = defaultdict(int), you don't need to worry about the else case:

def pick_up(self, item):
    if item in self.inv.keys():
        self.inv[item]  = 1
  • Related