我正在通過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