Tuesday, 21 February 2017

Python Program To Swap Two Variables

Python program to swap two variables

To swap two numbers in python, you can ask from user to enter the value of two numbers or you can manually put the values of two numbers, after that you can swap those two numbers using the third variable. Swapping of two numbers means placing the value of the first variable to the second variable and the value of the second variable to the first variable just by using another temporary variable. Or you can do it without using any third variable or temporary variable.
Python Program To Swap Two Variables
Python Program To Swap Two Variables

Following python program will ask the user to enter the value of two numbers to swap both the number.

 Python program to swap two variables 

while True:
print("Enter 'x' for exit.")
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
if num1 == 'x':
break
else:
number1 = int(num1)
number2 = int(num2)
swap = number1
number1 = number2
number2 = swap
print("Value of First and Second number after swapping:")
print("First Number =",number1,"\nSecond Number=",number2,"\n")

Python Program To Swap Two Variables(Using Temporary Variables)


x = 5
y = 10


temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

Python Program To Swap Two Variables Without Using Third Variables


  Python program to swap two variables Addition And Subtractions Method

x = 5
y = 10

x = x + y
y = x - y
x = x - y

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))


 Python program to swap two variables Using Xor Swap Method

x = 5
y = 10

x = x ^ y
y = x ^ y
x = x ^ y

print('The value of x after swapping: {}'.format(x))

print('The value of y after swapping: {}'.format(y))


 Python program to swap two variables Using Multiplication and Division Method

x = 5
y = 10


x = x * y
y = x / y
x = x / y
print('The value of x after swapping: {}'.format(x))

print('The value of y after swapping: {}'.format(y))

You May Also like  Basic Python Program For Practice

0 comments:

Post a Comment