The difference between a,b=b,a+b and a=bb=a+b of python

In python, the statements a,b=b,a+b and a=bb=a+b will execute two completely different results

First, let's first look at two examples and their explanations:

>>> a = 1
>>> b = 2
>>> a,b = b,a+b
>>> print(a,b)
2 3


>>> a = 1
>>> b = 2
>>> a = b
>>> b = a+b
>>> print(a,b)
2 4

It can be seen from the above results that a, b=b, a+b actually protect b first (assign the value of b to another variable), and then perform the remaining assignment operations. is the following code:

#a,b = b,a+b The code executed is as follows:
temp = b
b = a+b
a = temp

It can be understood as follows: first perform the calculation on the right side of the equal sign, and then perform the assignment operation separately

And a=bb=a+b, this statement does not need to be explained, it is a normal step-by-step assignment operation, after the first step of assignment, the value of a becomes 2, so the value of a+b assigned to b is naturally becomes 4

The interpretation of #a=bb=a+b is as follows:
a = 1
b = 2
a = b #The value of a becomes 2 at this time
b = a+b #The value of a is 2, the value of b is 2, the value of a+b is 4, and then assigned to b, b is 4

Second, the deviation of these two grammars in practice is shown:

Take the iterative method (note that it is not recursive) to construct the Fibonacci number sequence as an example:

Using a,b=b,a+b, you get the correct result:

>>> def fib(n):
	a,b = 0,1
	for i in range(1,n+1):
		b,a =a+b,b
		print(a)

		
>>> fib(12)
1
1
2
3
5
8
13
21
34
55
89
144

And using a=bb=a+b will produce the wrong sequence:

>>> def fib(n):
	a,b = 0,1
	for i in range(1,n+1):
		a =b
		b = a+b
		print(a)

		
>>> fib(12)
1
2
4
8
16
32
64
128
256
512
1024
2048
So in actual use, you have to figure out what kind of assignment you want to achieve.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326006343&siteId=291194637