如何在while循环中重置列表?

时间:2018-02-01 04:13:57

标签: python

我希望将值添加到列表中,但不会在每次循环回到开头时重置它。

def number():
    print "Input a number to add to a list. When done press q"
    loop = 0
    while loop == 0:
        loop = 1
        totallist = []
        x = raw_input()
        if x == 'q':
            print "Your total is:"
            return totallist
        else:
            totallist.append(number)
            loop = 0

2 个答案:

答案 0 :(得分:2)

totallist = []移出循环

答案 1 :(得分:2)

def number():
    print "Input a number to add to a list. When done press q"
    loop = 0
    totallist = [] # <-- Move it here
    while loop == 0:
        loop = 1
        # totallist = []
        x = raw_input()
        if x == 'q':
            print "Your total is:"
            return totallist
        else:
            totallist.append(number)
            loop = 0