Python program to swap two variables - By using arithmetic operators - Using multiplication and division operator
Python program to swap two variables - By using arithmetic operators - Using multiplication and division operator.
Python program to swap two variables - By using arithmetic operators - Using multiplication and division operator.
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To Swap the values of two variables using Addition and subtraction operator
P = P * Q
Q = P / Q
P = P / Q
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
Please enter value for P: 23
Please enter value for Q: 14
The Value of P after swapping: 14.0
The Value of Q after swapping: 23.0
The code you provided performs a swap of the values of two variables, P and Q, using addition and subtraction operators. Here's how the code works:
The user is prompted to enter a value for variable P using the input() function. The input() function waits for the user to enter a value and returns it as a string. Then, int() is used to convert the string input to an integer and assign it to the variable P. The same process is repeated for variable Q.
The swap operation begins. The current value of P is multiplied by the value of Q and the result is assigned back to P. This step effectively stores the original value of P multiplied by the original value of Q in P.
The current value of Q is obtained by dividing the new value of P (previously calculated) by the original value of Q. This step effectively stores the original value of P in Q.
The new value of P is obtained by dividing the new value of P by the current value of Q. This step effectively stores the original value of Q in P.
Finally, the swapped values of P and Q are printed using the print() function, along with appropriate messages.
In summary, this code performs a swap of two variables without using a temporary variable by utilizing multiplication, division, and the properties of mathematical operations.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.