[英]How can I turn this 'while' loop into a 'for' loop?
我正在练习 LPTHW,在练习 33 和最后一次学习练习中,他们要求将我必须的代码更改为“for”循环,而不是我编写的“while”循环。 这是我想出的代码:
numbers = []
def loop(i, x, new_num):
while i < x:
print "At the top i is %d" % i
numbers.append(i)
i = i + new_num
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
loop(0, 10, 6)
现在学习练习指导我,“现在,将它写成使用 for-loops 和 range。你还需要中间的增量器吗?如果你不摆脱它会怎样?”
这是我设法达到的程度,但我不知道我是否朝着正确的方向前进。 基本上只是在黑暗中拍摄:
numbers = []
new_numbers = [0]
def loop2():
for i in new_numbers:
print "At the top i is %d" % i
numbers.append(i)
我也不知道在哪里插入“范围”函数。 如果我设法把它变成一个 'for' 循环,它完全符合这个 'while' 循环代码的作用,它会是什么样子?
在您使用 while 循环的工作示例中,您在每个循环期间分配i = i + new_num
,因此您通过new_num
迭代i
。 这可以通过range
轻松复制。
range
最多需要 3 个参数: (starting_point, upper_bound, num_to_iterate_by)
在您的代码中, i
是起点, x
是上限, new_num
是您在每个循环中迭代的数字。
注意: for 循环中的第三个参数是可选的。 如果没有指定,Python 将使用 1 作为默认迭代器。
从您的代码更改:
while i < x:
with for i in range(i, x, new_num):
在第 4 行i = i + new_num
——
numbers = []
def loop(i, x, new_num):
for i in range(i, x, new_num):
print "At the top i is %d" % i
numbers.append(i)
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
loop(0, 10, 6)
输出:
At the top i is 0
Numbers now: [0]
At the bottom i is 0
At the top i is 6
Numbers now: [0, 6]
At the bottom i is 6
The numbers:
0
6
通过使用 for in range => for i in range(x,y)
numbers = []
def loop(i, x, new_num):
for i in range(i, x):
print "At the top i is %d" % i
numbers.append(i)
i = i + new_num
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
loop(0, 10, 6)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.