We re-assign the value of the variable
x in the line 4, using the current value of
x (which is 1) and the value of
total (which is 3). After this re-assignment, the value of
x has changed and became 2.
Analogically, with re-assigning
y, using its current value and the current value of
total. Hence, now
y is equal 3-2, hence 1.
But ( total ) is now equal to 4 because now x is equal to 2 so y = 4 - 2 = 2, am I right?
total remains equal to 3, as we calculated it in the third line of the code, using still the old values of
y. We never re-calculated or re-assigned it after that. It is not re-calculated automatically only because we re-assigned
It will be a good idea to run this above code line by line and add a
print() in between each lines for each variable. You will understand better that way. If you have already tried that, great then.
But why we didn’t do the same thing ( re-assigning ) for total ( it is also a variable )?.. I am very sorry for not understanding.
I have done this but I still don’t understand why ( total ) didn’t change because of the new value of ( x )
Indeed, if after these 5 lines of code you insert this line:
total = x + y
it will be re-assigned! Well, it will be actually again equal to 3, but this time it’s because of
In this task it was not re-assigned, yes, but if you add this line of code, or if you re-assign also
y with some new values again, then
total will be definitely re-assigned.
From your explanation, I can understand that to re-assign a new value to an old variable I should make a new assignment statement for the old variable, and not because I changed the value of ( x ) the previous statements will change ( x in total = x + y is still equal to 1 ). Is it correct?
Absolutely! If you want to re-assign an old variable (here it is
total), you have to create a new assignment statement exactly for that variable. Otherwise, even if you change the other variables which were initially used for its calculation (here they are
y), nothing will be changed to that variable (to
total). Let’s say that variable just doesn’t know anything about changing
y untill you re-assign exactly it.
Thanks a lot … can I say that x and y in ( total = x + y ) still have their old values?
Yes, in that line of code they still have the old values.