【问题标题】:Python not running called functionPython没有运行被调用的函数
【发布时间】:2015-10-03 14:16:53
【问题描述】:

脚本一直运行,直到调用“takenotes”函数,然后在它应该运行该函数时停止。没有任何错误它只是停止。这是为什么呢?

# 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()

【问题讨论】:

  • payment = [20, 20, 20, 20] 不修改全局变量,使用global 或者更好地将值传递给函数main()
  • 实际上@imaluengo 这是错误的。 Code Review 是一个工作代码的站点,而不是失败代码的站点。这意味着:代码不仅必须运行,还必须产生正确的结果,因此这个问题对于Code Review 来说是不切实际的。更多信息请见:meta.stackoverflow.com/questions/253975/…
  • @Vogel612 哎哟!不知道这个,抱歉。完全认为CodeReview 实际上是审查代码并查找错误(正如您链接的问题所述,我是那些没有阅读 CodeReview 帮助的人之一,但我刚刚学到了一个很好的教训)。谢谢!在再次推荐codereview之前我会三思而后行! :P

标签: python function python-3.x


【解决方案1】:

它不会“停止”。 takenotes 致电main;它进入while循环内的for循环;第一轮,changeT - i 不大于 0,所以返回 True。由于您没有对来自main 的返回值进行任何操作,因此不会打印任何内容,并且程序结束。

【讨论】:

    【解决方案2】:

    首先,您需要一个global 语句来更改任何全局变量(如payment)。

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

    您的代码中也没有input() 函数。见the docs

    【讨论】:

      【解决方案3】:

      此脚本运行正确。它调用takenotes()函数然后正常执行(显示消息,设置local支付数组然后执行main()函数)。 你可以在this online Python interpreter 上查看。你也可以一步一步执行它here,看看你的脚本到底做了什么。

      此外,当您要编辑全局变量时,您必须使用 global 语句。阅读this SO question 的答案以获取更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 2019-10-17
        • 2017-04-18
        • 2011-12-30
        • 2018-02-10
        相关资源
        最近更新 更多