2012-07-28 186 views
-3

如何将此while循环转换为函数,以便多次调用它。将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 
+0

这实际上是一个非常有效和有趣的问题。不是OP所要求的内容,而是动态代码创建。 – Nav 2017-12-31 16:58:56

回答

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 

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

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