简体   繁体   中英

Assigning multiple variables in one line

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)
        f1 = f2
        f2 = f1 + f2

        i += 1
    return f3

returns 1, 2, 4, 8, while this:

def fibonacci(n):

    f1 = 0
    f2 = 1
    i = 1

    while i < n:
        print(f2)
        f1, f2 = f2, f1 + f2
        i += 1
    return f3

returns the Fibonacci sequence.

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 .

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.

The variables f1 and f2 simultaneously get the new values f2 and f1 + f2, the expression

f1, f2 = f2, f1 + f2.

Demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place . f1 + f2 use the f1 old value we don't use the f1 new value. The right-hand side expressions are evaluated from the left to the right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM