0
我在代码中遇到了这个熟悉的错误(TypeError:'int'object is not iterable),但无法弄清楚如何解决它。我试图加总市场上所有东西的价值,所以我设置了一个循环,将1只香蕉乘以4美元,然后从股票中减去一根香蕉,移动到下一个项目,并跳过剩余零库存的项目。我希望它继续下去,直到所有物品的库存为零,基本上增加了市场上所有物品的价值。 compute_total_value函数是应该执行此操作的函数,但会弹出错误消息。 以下是错误:复合函数:TypeError:'int'对象不可迭代
Traceback (most recent call last):
File "/Users/sasha/PycharmProjects/untitled2/shopping.py", line 62, in <module>
total_market_value = compute_total_value(market_items)
File "/Users/sasha/PycharmProjects/untitled2/shopping.py", line 49, in compute_total_value
while sum(stock[items]) != 0:
TypeError: 'int' object is not iterable
这里是我的代码:
# Here is the market
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_total_value(food):
total = 0
for items in food:
while sum(stock[items]) != 0: #error is on this line
if stock[items] != 0:
total += prices[items]
stock[items] -= 1
else:
continue
if sum(stock[items]) == 0:
break
return total
market_items = ["banana", "orange", "apple", "pear"]
total_market_value = compute_total_value(market_items)
print (total_market_value)
请编辑此给予正确的格式[MCVE。 – jonrsharpe
@ tony-barbarino请不要添加“谢谢你的帮助!”编辑时。编辑通常应该删除像这样的短语。 – Kenster
你的逻辑对我来说没什么意义,你想要的是当前市场清单的价值,即8.5,或者你想要的是股票中所有东西的价值,那就是81.5? – Copperfield