2016-11-04 100 views
5

我在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 

回答

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 

在第二個版本,在添加之前,3210被分配,所以這裏的第二個版本如何去:

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. 
+0

非常感謝,摩根。所以正確表達的優先順序首先是對的? – Kelvin

+0

@KelvinYe沒錯。 –

+0

沒問題,很高興我能幫上忙。 –