► Python program to swap two numbers without using temp variable (multiplication-division operation)
Steps followed:
1. take input from user and store in num1 and num2 variables
2. validate user input by converting to integer
3. multiply both numbers and store in num1 variable
4. divide num2 from num1 and store result in num2 to swap the value in num2 variable
5. now num2 have num1 value, divide num2 again from num1 and store result in num1 to swap the value in num1 variable
6. print values
#python program to swap two numbers without using temp variable (multiplication-division operation)
#getting input from user and storing in num1 and num2 variables
num1=input("Enter value for num1: ")
num2=input("Enter value for num2: ")
#validating user input
try:
num1=int(num1)
num2=int(num2)
print("you have entered valid numbers")
#multiply both numbers and store in num1 variable
num1 = num1 * num2
#divide num2 from num1 and store result in num2 to swap the value in num2 variable
num2 = num1 / num2
#now num2 have num1 value, divide num2 again from num1 and store result in num1 to swap the value in num1 variable
num1 = num1 / num2
#print result
print("num1 value is %d"%(num1))
print("num2 value is %d"%(num2))
except:
print("you have entered an invalid number")
Enter value for num1: 25
Enter value for num2: 35
you have entered valid numbers
num1 value is 35
num2 value is 25
Enter value for num1: x
Enter value for num2: d
you have entered an invalid number