我正在通过CodeAcademy的初学者Python课程进行工作。这是其中一项练习的一部分,您在杂货店“检查”,但我想要代码打印最终账单/“总计”而不是仅返回“总计”。我不明白为什么它不打印。我已经尝试在迭代之后将它放在最后,并且在这里,在递归中(在返回总数之前),以查看它是否会在每一步之后进行打印。当我运行这个代码时,没有任何显示。为什么我不能在函数内打印结果?
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
food = shopping_list
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print total
return total
编辑: 这些也没有给我读出:
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total #tried 0-5 indentations, same blank result
然而
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total #tried 0-5 indentations, same blank result
return total
print compute_bill(food)
返回
Total is $ 5.5
5.5
虽然 - 我没有找到一个解决方案...
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
return total
print "Total is $",compute_bill(food)
返回 总计为$ 5.5 ......但我很困惑,为什么我不能只是打印总变量,它应该已被更新。它为什么在那里工作,但不是作为功能的饲料。这只是一个练习中的问题,但我无法弄清楚为什么这样做。
谢谢!这在教程中没有明确说明,因为它们似乎主要是让我们在不调用它们的情况下创建函数。 – toonarmycaptain