為什么 while 條件不適用于這種情況?
def Fibonacci():
user = int( input("Type the length of Fibonacci numbers will be generated: ") )
fbnc_list = [0, 1]
_continue_ = True
while _continue_:
for n in range(0, user 1):
fbnc_list.append( fbnc_list[n] fbnc_list[n 1] )
#print(fbnc_list, len(fbnc_list), user)
if len(fbnc_list) == user: _continue_ = False
return (fbnc_list)
Fibonacci()
在評論行,我看到當我輸入 10 時,它應該在這種情況下中斷
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 10 10 len(fbnc_list) == user / 10 == 10.
所以 _continue 設定為 False 并且 while 應該停止。不是正在發生的事情。
uj5u.com熱心網友回復:
設定_continue_為False將在下一次迭代時停止while回圈,但不會跳出for回圈。
如果要立即停止回圈,則需要取消設定_continue_ 并立即中斷for回圈:
if len(fbnc_list) >= user:
_continue_ = False
break
請注意,您首先不需要兩個回圈 - 一個for回圈與您需要的其他專案一樣多的迭代(即所需數字的數量減去您開始的兩個)就足夠了:
def fibonacci(n):
fibs = [0, 1]
for _ in range(n - 2):
fibs.append(fibs[-2] fibs[-1])
return fibs[:n] # handles n < 2
print(fibonacci(int(input(
"Type the number of Fibonacci numbers to generate: "
))))
Type the number of Fibonacci numbers to generate: 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
uj5u.com熱心網友回復:
這個怎么樣?
def Fibonacci():
user = int( input("Type the length of Fibonacci numbers will be generated: ") )
fbnc_list = [0, 1]
_continue_ = True
while _continue_:
for n in range(0, user 1):
fbnc_list.append( fbnc_list[n] fbnc_list[n 1] )
#print(fbnc_list, len(fbnc_list), user)
if len(fbnc_list) == user: _continue_ = False;break
return (fbnc_list)
Fibonacci()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/426291.html
