Python没有运行被调用的函数

2024-04-29 13:33:04 发布

您现在位置:Python中文网/ 问答频道 /正文

脚本一直运行到调用“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()

Tags: ofthe函数inindexcashpaymentout
3条回答

此脚本运行正确。它调用takenotes()函数,然后正常执行(显示消息,设置localpayment数组,然后执行main()函数)。 你可以在this online Python interpreter上查这个。您还可以一步一步地执行它here,以查看您的脚本到底做了什么。你知道吗

此外,如果要编辑全局变量,则必须使用global语句。阅读this SO question的答案了解更多信息。你知道吗

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

payment = []

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

代码中也没有input()函数。见the docs。你知道吗

它不是“停下来”。takenotes调用main;它到达while循环中的for循环;第一轮changeT - i不大于0,因此返回True。由于没有对来自main的返回值执行任何操作,因此不会打印任何内容,程序将结束。你知道吗

相关问题 更多 >