Python (Fibo series): trying to understand the difference between a, b = b, a + b OR a = b & a = a + b

I am not sure what would be the appropriate heading for this question, and this may also be a repeated question. Therefore, please be guided accordingly.

I am new to python programming. I have this simple code to generate Fibonacci series.

1: def fibo(n):
2:    a = 0
3:    b = 1
4:    for x in range(n):
5:        print (a, end=' ')
6:        #a, b = b, a+b
7:        a = b
8:        b = a+b
9:    print()
10: num = int(input("enter n value: "))
11: print(fibo(num))

If I executed the above code as is, I get the following result

enter n value: 10
0 1 2 4 8 16 32 64 128 256 

If uncomment # 6 and comment lines # 7 and # 8, I get the actual fibo series.

enter n value: 10
0 1 1 2 3 5 8 13 21 34 

I would like to know what is the difference between

a, b = b, a + b 

and

a = b
b = a + b

Programming IDE: PyCharm Community 2017.3

+4
source share
5 answers
a = b
b = a + b

in fact:

a = b
b = b + b

What would you like:

a = b
b = old_value_of_a + b

When you do this a, b = b, a + b he really does:

tmp_a = b
tmp_b = a + b
a = tmp_a
b = tmp_b

+6

7 b a, 8 b b.

6 = , Fibo.

+4

Assignment Statementments . ,

>>> a = 5
>>> b = 6
>>> a = b

b , a . . .

>>> hex(id(a)), hex(id(b))
>>> ('0x1002739e0', '0x1002739e0')

, , is

>>> a is b
>>> True

.

>>> a, b = b, a + b 

b a (a+b) b. , . , .

>>> a is b
>>> False

>>> hex(id(a)), hex(id(b))
>>> ('0x1002739e0', '0x2008739t0')

 >>> a = b
 >>> b = a + b

b a, (a+b) - b. , a b . , b = b + b.

+2

,

a = 10
b = 20

a = b
b = a+b

print (a)
print (b)

a = 10 a = 20, python , a 10 20

a=20
b=40

a = 10
b = 20

a,b = b,a+b

print (a)
print (b)

it will be the assignment of values ​​in one line, so the values ​​a and b will be exactly used from the fact that it is initialized above, and the result will be similar which is the correct solution

a=20
b=30
0
source

I think string #is a python solution. But if you are confused, you can use a variable that is temporary. you can assign a value tempearlier, then you can change the values

0
source

Source: https://habr.com/ru/post/1691664/


All Articles