将while循环转换为函数

时间:2012-07-28 13:57:32

标签: python python-2.7

如何将此循环转换为函数,因此我可以多次调用它。

i = 0
numbers = []
while i < 6:
    print "At the top of i is %d" % i
    numbers.append(i)


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

print "The numbers: "

for num in numbers:
    print num

2 个答案:

答案 0 :(得分:0)

def fun_name():
    i = 0
    numbers = []
    while i < 6:
        print "At the top of i is %d" % i
        numbers.append(i)
        i = i + 1
    print "Numbers now: ", numbers
    print "At the bottom i is %d" % i

    print "The numbers: "

    for num in numbers:
        print num

您可以添加,删除所需的部分代码。您还可以返回一些值以在主程序中使用。

答案 1 :(得分:0)

def get_numbers(N):
  numbers = []
  while i < N:
    print "At the top of i is %d" % i
    numbers.append(i)
  print "Numbers now: ", numbers
  print "At the bottom i is %d" % i

但是在python中有alreyady这样的函数,这个函数是range