方向挖所以我檢查了,你鏈接到Python的堅硬方式網站上的問題......我覺得他實際上只是要求你重新寫了使用for循環和範圍在這種情況下,你可以做這樣的事情原創劇本:
numbers = []
for i in range(6):
print "at the top i is", i
numbers.append(i)
print "numbers now", numbers
print "finally numbers is:"
for num in numbers:
print num
如果您運行,你會得到這樣的輸出:
$ python loops.py
at the top i is 0
numbers now [0]
at the top i is 1
numbers now [0, 1]
at the top i is 2
numbers now [0, 1, 2]
at the top i is 3
numbers now [0, 1, 2, 3]
at the top i is 4
numbers now [0, 1, 2, 3, 4]
at the top i is 5
numbers now [0, 1, 2, 3, 4, 5]
finally numbers is:
0
1
2
3
4
5
要回答你的問題有關的增量聲明,如果有必要,試試這個:
for i in range(6):
print "at the top i is", i
numbers.append(i)
i += 2
print "numbers now", numbers
print "at the bottom i is", i
print "finally numbers is:"
for num in numbers:
print num
,你會得到這樣的一些輸出:
$ python loops.py
at the top i is 0
numbers now [0]
at the bottom i is 2
at the top i is 1
numbers now [0, 1]
at the bottom i is 3
at the top i is 2
numbers now [0, 1, 2]
at the bottom i is 4
at the top i is 3
numbers now [0, 1, 2, 3]
at the bottom i is 5
at the top i is 4
numbers now [0, 1, 2, 3, 4]
at the bottom i is 6
at the top i is 5
numbers now [0, 1, 2, 3, 4, 5]
at the bottom i is 7
finally numbers is:
0
1
2
3
4
5
你看這是怎麼回事在這?請記住,範圍函數產生如下列表:
範圍(6) - > [0,1,2,3,4,5]。
這是Python for語句知道如何迭代的東西(他們稱這些類型的東西爲iterable)。無論如何,變量i被綁定到範圍(6)中的一個項目(即列表[0,1,2,3,4,5]),每次迭代。即使你在for循環中對我做了些什麼,它也會被迭代到iterable中的下一個項目。所以增量聲明絕對沒有必要。在這種情況下,無論我是什麼,它都會增加2,但無論如何,它都會像正常情況一樣反彈。
好,畢竟這裏是我改變你的具體代碼的改變,每次改變迭代器的時候都使用while循環來使用帶有範圍的for循環。
我認爲你只是通過瀏覽鏈接到的在線書籍的前幾章來介紹函數,但是如果在還沒有看到遞歸之前可能會有點混淆。再次調用函數之前的if語句是保持當前值超出範圍內的值,這會給你一個關於超過最大遞歸深度的錯誤(python這樣做是爲了防止出現堆棧溢出錯誤我很確定)。
最後一點可以做這樣的事情與範圍:
範圍(0,10,2) - > [0,2,4,6,8]
其下面我使用:
def my_loop(max, current=0, increment=1, numbers=[]):
for x in range(current, max, increment):
print "at the top, current is %d" % current
numbers.append(current)
increment = int(raw_input("Increase > "))
current += increment
print "numbers is now: ", numbers
print "at the bottom current is %d" % current
break
if current < max:
my_loop(max, current, increment, numbers)
else:
print "no more iterating!"
max = int(raw_input("Type in max value for the loop > "))
my_loop(max)
我不認爲我會永遠這樣做,但這至少是一件有趣的事情。
我想不出任何辦法的參數(P)轉成'for'循環這個(除非你想在那裏放一個'break') – mgilson
這是因爲'for'循環爲每次迭代設置'i'。它不會知道也不在乎你在循環中改變它。 –
*「事情是我想用for循環代替while循環」 - 爲什麼? – poke