CPSC 203: Introduction to computers |
An additional temporary variable is needed to store the value of one of the variables. Remember that a variable can only store one value at a time. If you use only two variables then copying the value of one variable into the other will result in one value being lost.
Incorrect approach:
def start (num1, num2):
print num1, num2
num1 = num2 <== Problem: The original value stored in num1 is now lost
num2 = num1 <== This merely copies the original value stored in num2 back into num2
print num1, num2 <== This just displays the original value stored in num2 twice!
Correct approach:
def start (num1, num2):
print num1, num2
temp = num1 <== Stores the current value of num1 in temp
num1 = num2 <== The value in num2 is stored in num1 (what was previously in num1 is now gone)
num2 = temp <== The previous value stored in num1 has been copied into temp which in turn is copied into num2
print num1, num2