在函数中放置一个 while 循环
Placing a While-loop Inside a Function
我是编程新手,想在函数内放置一个 while 循环,以便我可以调用该函数。下面是我写的代码。循环本身工作正常,但是当我尝试将它放入函数中时,列表 'numbers' 永远不会被附加。
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
你有函数定义,但没有调用它
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))
我是编程新手,想在函数内放置一个 while 循环,以便我可以调用该函数。下面是我写的代码。循环本身工作正常,但是当我尝试将它放入函数中时,列表 'numbers' 永远不会被附加。
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
你有函数定义,但没有调用它
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))