[英]Changing the range of a for loop based on the length of a list for Python
[英]Why there is no increment in the range of a loop, with its range being length of the loop,even though the length gets incremented inside the loop?
我是一個初學者,我自己嘗試了這個斐波那契數列,但是為什么即使列表的長度增加,變量 b=len(e)+5 的值也沒有增加。 為什么它不影響 for 循環的范圍。
e=[0,1]
a=1
b=len(e)+5
n=int(input('enter a no.'))
for i in range(a,b):
print(b)
if n<=len(e):
print(e[n-1])
break
else:
e.append(e[i-1]+e[i])
try:
if e[len(e)-1]==e[n-1]:
print(e[n-1])
break
except:
pass
我希望我對這個問題很清楚。 由於我是初學者,因此歡迎任何相當簡單的建議。 如果有什么我做錯了,也請指出。 謝謝你
簡單的代碼
e = [0,]
a, b = 0, 1
n = int(input('enter a no.'))
for i in range(1, n):
a, b = b, a + b
e.append(a)
print(e[n-1], e)
結果是
21 [0, 1, 1, 2, 3, 5, 8, 13, 21]
嘿@Jayasri Palanisamy b
的值沒有增加的原因是因為它只執行一次。 當b= len(e)+5 = 7
時。
e=[0,1]
a=1
n=int(input('enter a no.'))
b = len(e)+n
for i in range(a,b):
print(b)
if n<=len(e):
print(e[n-1])
break
else:
e.append(e[i-1]+e[i])
try:
if e[len(e)-1]==e[n-1]:
print(e[n-1])
break
except:
pass
這將為您提供正確的答案,但這也不是一個好的解決方案(我的意思是有一種方法可以做到這一點並且更簡單)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.