Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable assignment query in python

I am writing Fibonacci code in python. The below solution is mine.

enter image description here

While the other below solution is from python.org.

enter image description here

Can anyone tell me why it yields a different answer even though the logic of assigning the variables is the same?

like image 666
Ryusei Nakamura Avatar asked Nov 29 '22 09:11

Ryusei Nakamura


2 Answers

The lines

a = b # Assigns the value of 'b' to 'a'
b = a + b # Adds the new value of 'a' to 'b'

whereas,

a, b = b, a+b Assigns the value of b to a. Adds the existing value of a to b.

like image 35
sachin_hg Avatar answered Dec 01 '22 23:12

sachin_hg


Those two programs are not equivalent. The right hand side of the equals (=) is evaluated all together. Doing:

a=b
b=a+b

Is different from:

a,b = b,a+b

This is in reality the same as:

c = a
a = b
b = b + c

Your example is actually covered on the Python documentation:

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

like image 135
João Almeida Avatar answered Dec 01 '22 23:12

João Almeida