[英]Python function returns True or 1 as None, while returning False and 0 correctly
[英]Why is the dictionary returning None when using the function, while it returns what I want inside that function in 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.