【发布时间】:2018-09-21 19:34:07
【问题描述】:
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
print("Inventory:")
item_total = 0
for k, v in inventory.items():
print(str(v) + " " + k)
item_total += v
print("Total number of items: " + str(item_total) + '\n')
displayInventory(stuff)
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = {'gold coin': 42, 'rope': 1}
def addToInventory(ram, addedItems):
for itemindex in addedItems:
if itemindex not in ram:
ram[itemindex] = 0
ram[itemindex] = ram[itemindex] + 1
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
当我这样做时,它会返回这样的错误......
Inventory:
1 rope
6 torch
1 dagger
12 arrow
Total number of items: 62
Inventory:
Traceback (most recent call last):
File "python", line 33, in <module>
File "python", line 8, in displayInventory
AttributeError: 'NoneType' object has no attribute 'items'
这是没有意义的,考虑到当您将inv 更改为'abc' 或除 inv 之外的任何其他内容时,错误消失并且代码运行顺利。
【问题讨论】:
-
请复制粘贴控制台输出,不要发布它的图像。
-
你得到错误的原因是因为
addToInventory确实不返回一些东西显式,所以它返回None。
标签: python arrays python-3.x dictionary for-loop