python - for计算斐波那契数列
巴扎黑
巴扎黑 2017-04-18 10:20:44
0
3
896
fibs = [0,1]
for i in range(8):
    fibs.append(fibs[-2] + fibs[-1])
    print(fibs)

这段代码,for是怎么进行循环的?还有i在里面是个什么角色?求解答

巴扎黑
巴扎黑

reply all(3)
黄舟

If a list or tuple is given, we can traverse the list or tuple through a for loop. This traversal is called iteration. Iteration is done using for ... in. range(8) is a list[0, 1, 2, 3, 4, 5, 6, 7], i is a variable, and each round takes a number from ragne(8) to participate in the subsequent operations. This cycle takes a total of Count eight rounds (0~7) for 8 numbers.

迷茫

Although I don’t know python, my translation into js should be similar to this

fibs = [0, 1]
for(let i of new Array(8) ){
  fibs.push(fibs[fibs.length-2] + fibs[fibs.length-1])
  console.log(fibs)
}

The for loop only determines the number of loops, so i is not specifically used in the loop!

洪涛

Brother Huang, please listen
>>> range(8)
[0, 1, 2, 3, 4, 5, 6, 7]

range(8) in Python 2 is a list
for loop iterates this list. i is a variable.
Loop once, the i value starts from the first element and ends with the last element. That is, the value of i takes the value from range(8)[0] to range(8)[7]

In Python 3,
>>> range(8)
range(0, 8)
range(8) is a range object
Add a print(i) to see the change in the value of i in the loop.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template