How to swap the values of two variables using only two variables. Please note this will only work with numbers. Say will have two variables, varA and varB; We want the value of varA to equal the value of varB and varB to equal the value of varA. Now in most programs we would just use a third variable, varC. With 3 variables it would be as easy as: varC = varA varA = varB varB = varC With two variables we cannot store the temporary value, so we use the following instead: varA = varA + varB varB = varA - varB varA = varA - varB In my program you can see that varA stores the value of A and B (Total of both), then varB = the total value - the original varB value. Then varA can be set to the total - the value of varB which now has the original value of varA. |
Python Tutorial >