
Overwriting variable values
After assigning a value to a variable, you can assign a different value to the same variable. Let's check how this works.
Code (Example 1)
The code explained below assigns values to each variable as before, but does not overwrite the values of the variables.
(In the author's environment, a new file named “sec01_learning03_variables.py” has been created.)
numA = 2
numB = numA + 5
print(numA)
print(numB)
When you run this code, the results “2” and “7” will be output as shown in the figure below.

Let's go through the steps of this code one by one.
numA = 2
First, “2” is assigned to “numA.”
numB = numA + 5
In the next line, Python calculates the right side of the expression first. (Note: Not limited to Python, programs always calculate the right side of an assignment expression first, and then assign the result to the variable.)
Therefore, first perform “numA + 5.” Since “numA” is assigned the value “2,” performing “2 + 5” results in “7.” Then, assign “7” to “numB.”
Incidentally, in the second line, “numA” is referenced for the calculation on the right side, but no value is assigned to “numA” here. Therefore, the value of “numA” remains “2.”
From this processing flow, “2” for “numA” and “7” for “numB” are displayed on the TERMINAL.
Code (Example 2)
Next, add the code to the third line.
In the third line, a value is assigned to the variable “numB.” Since this variable already has a value assigned to it, the new value will overwrite the existing one.
numA = 2 # numA: 2
numB = numA + 5 # numA: 2, numB: 7
numB = numA - numB
print(numA)
print(numB)
Let's confirm the processing flow. The processing up to the second line of the above code is the same as before, with “2” assigned to “numA” and “7” assigned to “numB.”
As for the third line, Python calculates the right side first, as in the previous case. “numA - numB” refers to the values assigned to each variable, resulting in “2 - 7,” which is calculated as “-5.” Then, “-5” is assigned to “numB.”
Therefore, the output of the last two lines of “print” will be “2” for “numA” and “-5” for “numB”.

The above is how variables are overwritten.