-3

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

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
4

2 回答 2

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

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

于 2012-07-28T14:03:02.667 回答
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 中已经有这样的函数了,这个函数是range.

于 2012-07-28T14:07:03.430 回答