In-Place Operators | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

In-Place Operators

x = 2 x += 3 x += 4 x += 5 x += (x+x) print(x) output = 42 Why?

27th Jul 2020, 10:40 AM
Sean Lim
Sean Lim - avatar
3 Answers
+ 14
Sean Lim 1. x = 2 2. x += 3 ( x = 5 ) By this statement it simply means that (x = x + 3). Previous Value of x is 2 . It evalute as ( x = 2 + 3 ) that's why x = 5 3. x += 4 => ( x = 9 ) Previous value of x is 5 and 4 is added which becomes 9. 4. x += 5 => ( x = 14 ) 5 is added to its previous value 9. 5. x += ( x+x ) => x = 14 + ( 14+ 14) That's why 42 is assign to x. And output is x = 42.
27th Jul 2020, 10:58 AM
Vinesh Wadhwani
Vinesh Wadhwani - avatar
+ 2
X =2..5..9..14 And finally(14 + 2*14)=42
27th Jul 2020, 10:58 AM
Oma Falk
Oma Falk - avatar
+ 2
Thanks everybody, you guys/gals are amazing. I missed out on the part where I had to add the 14 to (14+14).
27th Jul 2020, 11:09 AM
Sean Lim
Sean Lim - avatar