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

30 lines
773 B
Python

import sys
tests = [
{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12},
{'rope': 1, 'torch': 6, 'gold coin': "a", 'dagger': 1, 'arrow': 12},
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}"
valid = True
for inventory in tests:
print(f"Testing inventory '{inventory}': ")
valid, msg = displayInventory(inventory)
print(msg)
if not valid:
sys.exit(1)