Python

《Python编程快速上手—让繁琐工作自动化》第5章实践项目答案

2019-11-04  本文已影响0人  simon_xu0559

5.6 好玩游戏物品清单

def displayInventory(dict_items):
    total_number = 0
    for key, value in dict_items.items():
        print(f'{value} {key}')
        total_number += value
    print(f'Total number of items: {total_number}')
    return


def addToInventory(dict_items, addeditems):
    for item in addeditems:
        dict_items.setdefault(item, 0)
        dict_items[item] += 1


stuff = {'rope': 1, 'torch': 6, 'dagger': 1, 'gold coin': 42, 'arrow': 12}
displayInventory(stuff)

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
print(dragonLoot)
addToInventory(stuff, dragonLoot)
displayInventory(stuff)

程序运行结果

1 rope
6 torch
1 dagger
42 gold coin
12 arrow
Total number of items: 62
['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
1 rope
6 torch
2 dagger
45 gold coin
12 arrow
1 ruby
Total number of items: 67

Process finished with exit code 0
上一篇下一篇

猜你喜欢

热点阅读