automate-boring-stuff/exercises/ex05/ex05c.py

46 lines
1.2 KiB
Python
Raw Normal View History

2023-04-20 11:08:00 -06:00
"""
Practice Projects: List to Dictionary Function for Fantasy Game Inventory
Page 128
"""
2023-03-02 18:55:19 -06:00
import sys
2023-04-20 11:08:00 -06:00
dragonLoot = ["gold coin", "dagger", "gold coin", "gold coin", "ruby"]
2023-03-02 18:55:19 -06:00
tests = [
2023-04-20 11:08:00 -06:00
{"rope": 1, "torch": 6, "gold coin": 42, "dagger": 1, "arrow": 12},
{"rope": 1, "torch": 6, "gold coin": "a", "dagger": 1, "arrow": 12},
2023-03-02 18:55:19 -06:00
None,
]
def displayInventory(inventory):
msg = "Inventory:\n"
total = 0
if not isinstance(inventory, dict):
return False, "Invalid inventory type"
for item, amount in inventory.items():
msg += f"{amount} {item}\n"
if not isinstance(amount, int):
return False, f"Invalid amount for '{item}'"
total += amount
return True, f"{msg}Total number of items: {total}"
def addToInventory(inv, items):
for item in items:
inv.setdefault(item, 0)
inv[item] += 1
return inv
valid = True
for inventory in tests:
print(f"Testing inventory addition with '{dragonLoot}': ")
valid, msg = displayInventory(inventory)
if valid:
inventory = addToInventory(inventory, dragonLoot)
valid, msg = displayInventory(inventory)
print(msg)
if not valid:
sys.exit(1)