在函数内部放置while循环

时间:2015-03-09 03:05:59

标签: python list function while-loop

我是编程新手,想在内部函数中放置一个while循环,所以我可以调用该函数。以下是我编写的代码。循环本身工作正常,但列表的数字'当我尝试将它放入函数中时,永远不会附加。

numbers = []

def loop_function(numbers):
    x = 6
    i = 0
    while i < x:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d\n" % i

    return numbers

print "The numbers: " 

for num in numbers:
    print num

1 个答案:

答案 0 :(得分:2)

你有功能定义,没有调用它

numbers = []

def loop_function(numbers):
    x = 6
    i = 0
    while i < x:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d\n" % i

    return numbers

loop_function(numbers)
print "The numbers: " 

for num in numbers:
    print num

但这仍然不是一段好的代码

编辑: 如果你的函数看起来像这样,你会怎么说?

def loop_function(num):
    num.extend(range(6))