Python多变量赋值混淆

时间:2016-11-04 14:31:53

标签: python

我在Python的第一天与一个非常简短的例子混淆。希望任何人都可以提供一些解释,说明为什么这几个版本之间存在一些差异。请!

V1:输出为1,1,2,3,5,8

a, b = 0, 1
while b < 10:
    print(b)
    a, b = b, a+b

V2:输出为1,2,4,8

a, b = 0, 1
while b < 10:
    print(b)
    a = b
    b = a+b

1 个答案:

答案 0 :(得分:5)

在第一个版本中,首先评估右手,因此在添加时b没有增加。

逐步完成第一个版本的迭代:

1

a = 0
b = 1
a, b = 1, 1  # b is 1, and a is 0

2

a = 1
b = 1
a, b = 1, 2  # b is 1 and a is 1

3

a = 1
b = 2
a, b = 2, 3  # b is 2 and a is 1

在第二个版本中,b是在添加之前分配的,所以这里是第二个版本的用法:

1

a = 0
b = 1
a = b  # a is now 1.
b = a + b  # b is now 2, because both a and b are 1.

2

a = 1
b = 2
a = b  # a is now 2.
b = a + b  # b is now 4, because both a and b are 2.