2017-07-24 39 views
-2

當我運行我的代碼,下面的代碼應該保持遍歷只要使用功能爲去等於「不」:這個功能,如果語句沒有做它應該

def use(): 
     item = input("What would you like to buy in bulk? ") 
     purchase.append(item) 
     done() 

    def done(): 
     global go 
     go = input("Is that all? ") 
    use() 
    if go == "no": 
     use() 

我不知道爲什麼它只運行兩次item = input("What would you like to buy in bulk? ")

任何人都可以幫忙。

+0

indentation is corrupt;請更正,所以有人可以幫助你。 – Daniel

+0

縮進必須關閉,否則if語句無法訪問。 – ajax992

+0

刪除if條件之上的'use()'。您的代碼沒有達到if條件 – anon

回答

0

你的問題的簡短答案是,你只能撥打use()兩次。 if不是像while這樣的循環結構,並且您沒有遞歸調用。因此函數調用只能達到兩次。

您可以通過放置到done()呼叫在use()年底內有條件內done()以產生循環添加一個循環,並調用use()

purchase = [] 

def use(): 
    item = input("What would you like to buy in bulk? ") 
    purchase.append(item) 
    done() 

def done(): 
    go = input("Is that all? ") 
    if go == "no": 
     use() 

# Here is the first call to use() that will be reached: 
use() 

# This will be reached after the first time 'no' is not given to done() 
print(purchase) 

另請注意,我添加了購買清單,以便撥打purchase.append(item)電話。

0

如果您想重複某些操作,請使用循環,例如, while

def input_purchases(): 
    purchase = [] 
    while True: 
     item = input("What would you like to buy in bulk? ") 
     purchase.append(item) 
     go = input("Is that all? ") 
     if go != "no": 
      break 
    return purchase 

purchase = input_purchases() 
相關問題