Home > Blockchain >  How to let user input and delete the inventory he/she want to remove any items from the inventory
How to let user input and delete the inventory he/she want to remove any items from the inventory

Time:04-04

I am new on python. I want to add a function named delFromInventory(inventory, deletedItems), whereby the deletedItems parameter is the input from the user if he/she want to remove any items from the inventory. This function should be callback before displayInventory(). May i know how and where should i write the script?

Below is my current code.

def displayInventory(inventory):
    print('Inventory:')
    item_total = 0
    for k, v in inventory.items():
        print(str(v)   ' '   k)
        item_total  = v
    print('Total Items: '   str(item_total))


def addToInventory(inventory, added_items):
    for loot in addedItems:
        if loot not in inv:
            inv[loot] = 1
        else:
            inv[loot]  = 1

inv = {'gold coin': 42, 'rope': 1}
addedItems = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

addToInventory(inv, addedItems)
displayInventory(inv)

CodePudding user response:

delFromInventory() is very similar to addToInventory(). You need to check whether the key exists within the dictionary and if it does not you can't remove anything, obviously. If it does, we need to check if the count would be 0 (or less than 0 if we were to have an element with count 0 in the dictionary) after deletion and if that's the case we can remove that key from the inventory because the count is (or already was) 0. In all other cases we can just decrement the count by 1.

def displayInventory(inventory):
    print('Inventory:')
    item_total = 0
    for k, v in inventory.items():
        print(str(v)   ' '   k)
        item_total  = v
    print('Total Items: '   str(item_total))


def addToInventory(inventory, added_items):
    for loot in addedItems:
        if loot not in inv:
            inv[loot] = 1
        else:
            inv[loot]  = 1


def delFromInventory(inventory, items_to_remove):
    for item in items_to_remove:
        if item not in inventory:
            print(f"Can't remove {item} from inventory as it is not in inventory")
        else:
            count = inventory[item]
            if count - 1 <= 0:
                del inventory[item]
            else:
                inventory[item] = count - 1

inv = {'gold coin': 42, 'rope': 1}
addedItems = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

addToInventory(inv, addedItems)

displayInventory(inv)
delFromInventory(inv, ["joystick", "dagger", "ruby", "ruby"])
displayInventory(inv)

Expected output:

Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total Items: 48
Can't remove joystick from inventory as it is not in inventory
Can't remove ruby from inventory as it is not in inventory
Inventory:
45 gold coin
1 rope
Total Items: 46
  • Related