简体   繁体   中英

What's the difference between this 2 code

I have 2 code which is a different and I get different answers. I wonder what the difference is

x, y = 0, 1

while y < 50:
    print(y)
    x, y = y, x + y

x=0
y=1

while y < 50:
    print(y)
    x=y
    y=x+y

first code output is: 1 1 2 3 5 8 13 21 34

and two code: 1 2 4 8 16 32

x, y = y, x+y constructs an tuple on the RHS using the original values of x and y before performing any assignments to x and y on the left. It's equivalent to

new_y = y
new_x = x + y
x = new_x
y = new_y

With

x = y
y = x + y

your new value of y is adding the new value of x ( which is y ) to y ; you've already lost the old value. You would need to write instead

old_x = x
x = y
y = old_x + y

The tuple unpacking is a way to avoid the need for the temporary variable old_x .

The difference is the order of evaluation.

In the first example, you have this:

x, y = y, x + y

This is evaluating two expressions on the right hand side, and then storing them into a tuple, then unpacking them on the left hand side.

Because this is all part of one "master" expression (the tuple), no variables are updated during the construction of the tuple. This means:

y, x+y evaluates as (old value of y), (old value of x) + (old value of y)

Once the tuple has been constructed, both x and y are set.

Your second example makes things explicitly different by putting the assignments into different statements. This causes the value of x to be changed before the computation of the second assignment:

x=y
y = x + y

This is equivalent to:

x = (old value of y)
y = (old value of y) + (new value of x == old value of y)

Which sets y to 2 * y .

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