为什么使用函数时字典返回None,而在Python中它返回我想要的函数内的内容



我正在学习Python,我正在尝试写一些程序来管理"库存"。我有一种方法来改变列表到字典,它加起来的值,但最后返回None。代码看起来像这样:

def addToInventory(inventory, addedItems):
backpack = {}
for i in addedItems:
backpack.setdefault(i, 0)
backpack[i] += 1
print(backpack)
for k, v in backpack.items():
if k not in inventory.keys():
inventory.setdefault(k, v)
elif k in inventory.keys():
inventory[k] += backpack[k]
print(inventory)

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
print(inv)

print(inventory)返回我想要的,但是print(inv)返回None。你能告诉我我做错了什么吗?对不起,如果这是微不足道的。提前谢谢你。

def addToInventory(inventory, addedItems):
backpack = {}
for i in addedItems:
backpack.setdefault(i, 0)
backpack[i] += 1
print(backpack)
for k, v in backpack.items():
if k not in inventory.keys():
inventory.setdefault(k, v)
elif k in inventory.keys():
inventory[k] += backpack[k]
print(inventory)
return inventory # This was missing!!

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
print(inv)

相关内容

  • 没有找到相关文章

最新更新