[英]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.