You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《Python编程快速上手》中addToInventory函数输出出现None值的问题咨询

为什么我的addToInventory函数输出末尾会出现None?

这个问题其实很常见——你看到的None是因为你用print()包裹了函数调用,而你的函数没有返回任何值。

问题根源

在Python中,如果一个函数没有写return语句,它默认会返回None。你的addToinventory函数(注意这里拼写和题目要求的addToInventory有点小差异)内部完成了库存更新和打印操作,但最后没有返回任何内容。当你执行print(addToinventory(inv, dragonloot))时,Python会先运行函数本身(输出那些库存行和总数),然后把函数的返回值(也就是默认的None)打印出来,这就是你看到末尾那个None的原因。

两种修正方案

方案1:让函数专注于更新库存,把打印逻辑移到外部(更符合代码规范)

函数的职责应该尽量单一,我们让addToInventory只负责更新库存并返回结果,打印的事情交给函数外部来做:

def addToInventory(inventory, addedItems):
    for item in addedItems:
        inventory.setdefault(item, 0)
        inventory[item] += 1
    # 返回更新后的库存字典
    return inventory

inv = {'gold coin': 42, 'rope': 1}
dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# 先获取更新后的库存
updated_inventory = addToInventory(inv, dragonloot)

# 单独处理打印逻辑
total_items = 0
for item, count in updated_inventory.items():
    print(f"{count} {item}")
    total_items += count
print(f'Total number of items: {total_items}')

方案2:直接调用函数,不要用print()包裹

如果你想保留函数内部的打印逻辑,只需要直接调用函数,不要把它放在print()里面:

def addToinventory(inventory, addedItems):
    for i in addedItems:
        inventory.setdefault(i, 0)
        inventory[i] += 1
    itotal = 0
    for k, v in inventory.items():
        print(str(v), k)
        itotal += v
    print('Total number of items', itotal)

inv = {'gold coin': 42, 'rope': 1}
dragonloot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

# 直接调用函数,不需要print包裹
addToinventory(inv, dragonloot)

这两种方案都能解决末尾出现None的问题,第一种更推荐,因为它让函数职责更清晰,后续如果需要复用库存更新的逻辑也更方便。

内容的提问来源于stack exchange,提问作者user18503685

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:57:43