Python program to swap two variables - By using arithmetic operators - Using multiplication and division operator
Python Operators in Python (Article) Operators in Python (Program)
153Program:
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)
Output:
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
Explanation:
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 theinput()
function. Theinput()
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 variableP
. The same process is repeated for variableQ
. -
The swap operation begins. The current value of
P
is multiplied by the value ofQ
and the result is assigned back toP
. This step effectively stores the original value ofP
multiplied by the original value ofQ
inP
. -
The current value of
Q
is obtained by dividing the new value ofP
(previously calculated) by the original value ofQ
. This step effectively stores the original value ofP
inQ
. -
The new value of
P
is obtained by dividing the new value ofP
by the current value ofQ
. This step effectively stores the original value ofQ
inP
. -
Finally, the swapped values of
P
andQ
are printed using theprint()
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.
This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.