【发布时间】:2022-10-06 02:51:36
【问题描述】:
第一次在这里发布海报和 Python 新手。
为了掌握 Python 的基础知识,我从阅读 Al Sweigart 的 Automate The Boring Stuff 开始,我认为我会尝试参与其中的一个迷你项目,那就是“Fantasy Inventory” “ 项目。我设法弄清楚它是如何通过一些试验和错误(以及大量谷歌搜索)工作的,但这是最终代码:
stuff = {\'rope\': 1, \'torch\': 6, \'gold coin\': 42, \'dagger\': 1, \'arrow\': 12}
def displayInventory(inventory):
total_items = 0
for item, quantity in inventory.items():
print(str(quantity) + \' \' + item)
total_items += quantity
print(\"Total number of items: \" + str(total_items))
displayInventory(stuff)
我决定尝试包含一个“珍贵矿物质”字典,这样它就可以为文本添加一点额外的味道,包括一个 if 和 elif 语句,如果preciousMineral 总数为 0 或大于 0。代码现在看起来像这样:
stuff = {\'arrows\': 41, \'sword\': 1, \'dagger\': 2, \'torch\': 1}
preciousMinerals = {\'rubies\': 0, \'emeralds\': 0, \'sapphires\': 0}
stuffAndMinerals = stuff|preciousMinerals
def displayInventory(inventory):
total_items = 0
for item, quantity in inventory.items():
print(str(quantity) + \' \' + item)
total_items += quantity
print(\'You have a total of \' + str(total_items) + \' items in your bag.\')
if str(quantity(preciousMinerals)) == 0:
print(\'You have no precious minerals.\')
elif str(quantity(preciousMinerals)) > 0:
print(\'You have some precious minerals in your bag.\')
print(\'You have: \' + str(quantity(preciousMinerals[0]) + \', \' +
str(quantity(preciousMinerals[1]) + \', \' +
str(quantity(preciousMinerals[2]) + \'.\'))))
displayInventory(stuffAndMinerals)
在添加珍贵矿物之前,代码运行流畅,没有错误。但是,我现在在线收到一个 \'TypeError: \'int\' object is not callable\' 错误:
if str(quantity(preciousMinerals)) == 0:
任何帮助将不胜感激!非常感谢。
-
quantity是一个整数变量,而不是一个函数。您需要if sum(preciousMinerals.values()):,并从您的最终打印语句中删除quantity((3 次)。quantity不参与其中。
标签: python list dictionary typeerror callable