2017-05-03 183 views
0

我正在通過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 ......但我很困惑,爲什麼我不能只是打印總變量,它應該已被更新。它爲什麼在那裏工作,但不是作爲功能的飼料。這只是一個練習中的問題,但我無法弄清楚爲什麼這樣做。

回答

1

在你的第一個例子,

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。你永遠不會調用這個函數。該函數在被調用時被執行,例如, compute_bill(["banana"])

+0

謝謝!這在教程中沒有明確說明,因爲它們似乎主要是讓我們在不調用它們的情況下創建函數。 – toonarmycaptain

1

我不知道我很明白的問題,但你說

但我很困惑,爲什麼我不能只是打印總變量,它應該已被更新。

如果你試圖從它不會工作之外的功能打印total,因爲total變量只在函數內部聲明。當你return total你允許你的其他代碼從你的函數外部獲取數據,這就是爲什麼print computeBill(food)確實工作。

編輯,如果你還希望在每次迭代打印總,您的代碼:

def compute_bill(food): 
    total = 0 
    for item in food: 
    if stock[item]>0: 
     total += prices[item] 
     stock[item] -=1 
     print "Total is $",total 

肯定應該有這個缺口,這意味着你將打印每次在for循環迭代時間(如果你保持原樣,它只會在for之後打印)。

1

print語句是函數compute_bill(..)的一部分,除非調用函數compute_bill(..),否則它將不會執行。

def compute_bill(food): 
    total = 0 
    for item in food: 
     if stock[item]>0: 
     total += prices[item] 
     stock[item] -=1 
    print "Total is $",total #this works 

compute_bill(food) # call the function it has the print statement 
相關問題