Predict the output of the following code:
def Swapper (X,Y=5) :
X=X+Y
Y=X-Y
return Y
A=10
B=15
B= Swapper (A,B)
print(A,B, sep = '^')
A= Swapper (A)
print(A,B,sep= '^', end='***')
Answer:
Answer by student
The output of the code is:
10^10
10^10***
Detailed answer by teachoo
-lock-
- The code defines a function named Swapper that takes two parameters X and Y, and returns the value of Y after swapping it with X. The parameter Y has a default value of 5, which means that if no argument is passed for Y, it will be assigned 5.
- The code then assigns 10 to A and 15 to B, and calls the Swapper function with A and B as arguments. The function swaps the values of A and B using the formula:
X=X+Y
Y=X-Y
This means that X becomes A+B (25), and Y becomes X-B (10). The function returns Y, which is 10, and assigns it to B. Therefore, after this call, A is still 10 and B is 10.
- The code then prints A and B separated by a ‘^’ symbol. The output is:
10^10
- The code then calls the Swapper function again, but this time only with A as an argument. Since no argument is passed for Y, it will take the default value of 5. The function swaps the values of A and 5 using the same formula as before. This means that X becomes A+5 (15), and Y becomes X-5 (10). The function returns Y, which is 10, and assigns it to A. Therefore, after this call, A is 10 and B is still 10.
- The code then prints A and B separated by a ‘^’ symbol again, but this time with an end parameter of “***” . This means that the output will end with “***”instead of a newline. The output is:
10^10***
- So, the final output of the code is:
10^10
10^10***
-endlock-