Home  >  Q&A  >  body text

python - for计算斐波那契数列

fibs = [0,1]
for i in range(8):
    fibs.append(fibs[-2] + fibs[-1])
    print(fibs)

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

巴扎黑巴扎黑2740 days ago856

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-18 10:22:44

    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.

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:22:44

    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!

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:22:44

    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.

    reply
    0
  • Cancelreply