Assigning multiple variables in one line

后端 未结 3 2016
闹比i
闹比i 2021-01-24 02:11

I am trying to make the Fibonacci sequence I don\'t get why this:

def fibonacci(n):
    f1 = 0
    f2 = 1
    i = 1

    while i < n:
        print(f2)
               


        
3条回答
  •  臣服心动
    2021-01-24 02:53

    In the first example, the value of f1 from the previous iteration is discarded before f2 is updated.

    f1, f2 = f2, f1 + f2
    

    can be seen as shorthand for

    tmp = f1
    f1 = f2
    f2 = tmp + f2
    

    if that helps it make more sense. The latter is what you'd have to do in many other languages to get the desired effect.

提交回复
热议问题