Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am not sure what would be an appropriate heading for this question and this can be a repeated question as well. So please guide 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 execute the above code as-is the result I get is as follows

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

If uncomment #6 and comment lines #7 and #8 the result I get is 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 used: PyCharm Community 2017.3

like image 620
aioracle Avatar asked Dec 13 '22 19:12

aioracle


2 Answers

a = b
b = a + b

is actually:

a = b
b = b + b

what you want is:

a = b
b = old_value_of_a + b

When you do a, b = b, a + b it really is doing:

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

which is what you want

like image 118
excalibur1491 Avatar answered Dec 18 '22 00:12

excalibur1491


In line 7, you've already assigned the value in b to a, so in line 8, new value for b is actually double the old b's value.

While in line 6, the values on the right side of = will be using the old values, that's why you could get Fibo series.

like image 39
nevets Avatar answered Dec 18 '22 00:12

nevets