Query related to statements | Python Language Forum
A
Amit Kumar Posted on 03/06/2022

Hi sir,

In Python are the below statements are same or what is the diffrence.

1. a=b
b=b+a

 

2. a,b=b,b+a

 

Eg: 

a = 0
b = 1
while b < 100:
print(b, end= '', flush=True)
a=b
b=b+a

this did not work , However below code works fine

 

a = 0
b = 1
while b < 100:
print(b, end= '', flush=True)
a,b=b,b+a




 


Y
Yogesh Chawla Replied on 03/06/2022

Hi Amit,

When we deal with expressions in python, everything to the right of the ‘=’ operator, i.e. the assignment operator,
is evaluated first before it is assigned to the variables on the left.

Additionally, when we use comma on the RHS, we’re telling python to create a tuple.
Using a comma on LHS tells python to unpack the tuple on the RHS into the variables on the LHS.

You will learn tuple in the coming modules. Just for your knowledge to answer this question,
Tuple is a collection of Python objects separated by commas and is immutable(once created doesn't alter)

Example
# One way to create tuple is
tup = 'a', 'b'
print(tup)

# Another way for doing the same - because tuple is identified by round brackets or parenthesis
tup = ('a', 'b')
print(tup)

#Same result will come

Now coming back to your question,

In a, b = b, a + b, the expressions on the right hand side is evaluated first before the values are assigned to the left hand side.
So it is equivalent to:

c = a + b
a = b
b = c

In your second example, the value of b already became a + b before it is given to a, that's the reason why it worked.

Run this in your first example, It will work:

a = 0
b = 1
while b < 100:
    print(b, end= ' ', flush=True)
    #a,b=b,b+a
    c = a + b
    a = b
    b = c

 


A
Amit Kumar Replied on 03/06/2022

Thanks :)