2015-10-03 75 views
0

腳本一直運行,直到調用'takenotes'函數,然後停止運行函數。沒有任何錯誤只是停止。爲什麼是這樣?Python未運行調用函數

# Please note that this only works in integer values, since there is no change in pence 
notes = (1,5,10,20,50) #Value of notes 
quantities = [10,8,5,5,1] #Quantities of notes 
# Defining variables 
notesout = [] 
total = 0 
x = -1 
payment = [] 
# This loop works out the total amount of cash in the cash register 
while (x < 4): 
     x += 1 
     calc = notes[x]*quantities[x] 
     total += calc 
mon_nd = 70 # Money needed 
def takenotes(): 
     print("Please input each notes value, when finished type \"stop\"") 
     # If input is an int then add to payment list, if not then work out the change 
     payment = [20,20,20,20] 
     main() 

def main(): 
     # Finds the value of the cash given 
     paymentV = sum(payment) 
     changeT = paymentV - mon_nd 
     # Change the quantities of the 'quantities' variable 
     for i in payment: 
       quantities[notes.index(i)] = quantities[notes.index(i)] + 1 
     while(changeT < 0): 
       # Works out what amount of change should be given 
       for i in reversed(notes): 
         if (changeT - i >= 0): 
           notesout.append(i) 
           quantities[notes.index(i)] = quantities[notes.index(i)]-1 
           changeT -= i 
         else: 
           return True 
     print(notesout) 
takenotes() 
+0

'payment = [20,20,20,20]'不會修改全局變量,請使用'global'或更好地將值傳遞給main()函數。 – bereal

+1

其實@imaluengo這是錯誤的。代碼審查是**工作**代碼的網站,而不是失敗的代碼。這意味着:代碼不僅必須運行,而且必須產生正確的結果,因爲這個問題對於[codereview.se]是不合理的。欲瞭解更多信息,請參閱:https://meta.stackoverflow.com/questions/253975/be-careful-when-recommending-code-review-to-askers?s=1|1.0000 – Vogel612

+0

@ Vogel612哎唷!不知道,對不起。完全認爲'CodeReview'實際上是審查代碼和發現錯誤(因爲你的鏈接問題說,我是那些沒有閱讀CodeReview的幫助,但我剛剛學到一個很好的教訓)之一。謝謝!在再次推薦codereview之前,我會三思而後行! :P –

回答

0

它不「停止」。 takenotes調用main;它進入while循環內部的for循環;第一次,changeT - i不大於0,所以它返回True。由於您沒有對main的返回值進行任何操作,因此不會打印任何內容,並且程序結束。

0

首先,您需要一個global語句來更改任何全局變量(如payment)。

payment = [] 

def takenotes(): 
    global payment 
    payment = [20, 20, 20, 20] 

您的代碼中也沒有input()函數。見the docs

0

此腳本運行正常。它調用takenotes()函數,然後正常執行(顯示消息,設置本地支付數組,然後執行main()函數)。 您可以在this online Python interpreter上查看。你也可以執行它一步一步的步驟here,看看你的腳本到底做了什麼。

另外,當您要編輯全局變量時,您必須使用全局語句。閱讀this SO question的答案瞭解更多信息。