Add / remove items in the list

I am trying to create a player who can add and remove items from their inventory. Everything works for me, I have only one small problem. Each time he prints the inventory, a "No" also appears. I already fiddled with it to try to remove it, but no matter what I do, the program always shows "No"! I know that I just missed something simple, but I canโ€™t understand what kind of life it is.

class Player(object): def __init__(self, name, max_items, items): self.name=name self.max_items=max_items self.items=items def inventory(self): for item in self.items: print item def take(self, new_item): if len(self.items)<self.max_items: self.items.append(new_item) else: print "You can't carry any more items!" def drop(self, old_item): if old_item in self.items: self.items.remove(old_item) else: print "You don't have that item." def main(): player=Player("Jimmy", 5, ['sword', 'shield', 'ax']) print "Max items:", player.max_items print "Inventory:", player.inventory() choice=None while choice!="0": print \ """ Inventory Man 0 - Quit 1 - Add an item to inventory 2 - Remove an item from inventory """ choice=raw_input("Choice: ") print if choice=="0": print "Good-bye." elif choice=="1": new_item=raw_input("What item would you like to add to your inventory?") player.take(new_item) print "Inventory:", player.inventory() elif choice=="2": old_item=raw_input("What item would you like to remove from your inventory?") player.drop(old_item) print "Inventory:", player.inventory() else: print "\nSorry, but", choice, "isn't a valid choice." main() raw_input("Press enter to exit.") 
+4
source share
2 answers

The problem is this:

 print "Inventory:", player.inventory() 

You tell Python to print the value obtained from player.inventory (). But your inventory () method just prints the inventory, it returns nothing, so the return value is implicitly missing.

You probably want to explicitly choose either this:

 print "Inventory:" player.print_inventory() 

Or, alternatively, you can return the string and do the following:

 print "Inventory:", player.inventory_as_str() 
+4
source

Could you replace the function:

 def inventory(self): for item in self.items: print item 

with this:

 def inventory(self): print self.items 

and then call:

 print "Inventory" player.inventory() 

Or you may have a function:

 def print_inventory(self): print "Inventory:" for item in self.items: print item 
0
source

Source: https://habr.com/ru/post/1304828/


All Articles