我正在http://automatetheboringstuff.com/chapter5/进行最后一次练习。出于某种原因,我无法让displayInventory(inv)
函数在addToInventory()
函数之外返回正确的值。
以下是代码:
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))
def addToInventory(inventory, addedItems):
for k in addedItems:
if k in inventory:
inv[k] = inv[k] + 1
print('You have ' + str(inv[k]) + ' ' + k + 's')
else:
print(k + ' is not in inventory')
inventory.setdefault(k, 1)
print()
displayInventory(inv) #does work
inv = {'gold coin': 42, 'rope': 1}
displayInventory(inv)
print()
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
print()
displayInventory(inv) #Doesn't work
我收到错误:AttributeError: 'NoneType' object has no attribute 'items'
看起来inv
字典是空的。为什么它被清空以及为什么价值在功能之外是不同的?
答案 0 :(得分:3)
您的addToInventory()
函数返回None
,因为您没有特定的return
声明。
由于该函数改变了字典,你应该不使用返回值;删除inv =
部分:
# ignore the return value; do not replace `inv` with it
addToInventory(inv, dragonLoot)