2015-10-03 37 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的答案了解更多信息。