Assigning multiple variables in one line

后端 未结 3 2019
闹比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 03:09

    In the latter example, the right hand side is evaluated first:

    f1, f2 = f2, f1 + f2
    

    So the value of f1 used in the calculation of f2 is the "old" value.

    In your code, when you do:

    f1 = f2
    f2 = f1 + f2
    

    the value of f1 has already changed when you go to evaluate the new value for f2.

提交回复
热议问题