让我们展开 for 循环,看看会发生什么:
a = 0
b = 1 # this is the first fibonacci number
# First iteration of for loop
c = a + b # c is now 1, the second fibonacci number
a = b # a is now 1
b = c # b is now 1
# Second iteration
c = a + b # c is now 2, the third fibonacci number
a = b # a is now 1
b = c # b is now 2
# Third iteration
c = a + b # c is now 3, the fourth fibonacci number
a = b # a is now 2
b = c # b is now 3
# Fourth iteration
c = a + b # c is now 5, the fifth fibonacci number
a = b # a is now 3
b = c # b is now 5
# Remaining 98 iteration omitted
您会看到,经过 4 次迭代后,我们得到了c
第 5 个斐波那契数。102 次迭代c
后将保持 103:d 斐波那契数。这就是为什么你使用range(102)
而不是range(103)
. 如果您希望您的斐波那契数列以 0 开头(有时会这样),即0, 1, 1, 3, 5
,您需要使用range(101)
.
python for 循环迭代一个序列,直到序列用完,或者 for 循环与break
语句一起过早退出。range(5)
创建一个包含 5 个元素的列表:[0, 1, 2, 3, 4]
,当与 for 循环一起使用时,会导致它重复 5 次。因此,以下示例中的循环体被评估了 5 次:
sum = 0
for i in range(5):
sum = sum + i
print sum
我们刚刚计算了第五个三角形数:10
更多关于 python for 循环的信息:
https ://wiki.python.org/moin/ForLoop