► Python program to swap two numbers without using temp variable (addition-subtraction operation)


Steps followed:
1. take input from user and store in num1 and num2 variables
2. validate user input by converting to integer
3. add both numbers and store in num1 variable
4. subtract num2 from num1 and store result in num2 to swap the value in num2 variable
5. now num2 have num1 value, subtract num2 again from num1 and store result in num1 to swap the value in num1 variable
6. print values


Program

#python program to swap two numbers without using temp variable (addition-subtraction 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")    
    
    #add both numbers and store in num1 variable
    num1 = num1 + num2

    #subtract num2 from num1 and store result in num2 to swap the value in num2 variable
    num2 = num1 - num2

    #now num2 have num1 value, subtract 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")
 


Output

Enter value for num1: 15
Enter value for num2: 18
you have entered valid numbers
num1 value is 18
num2 value is 15

 

Enter value for num1: x
Enter value for num2: y
you have entered an invalid number





Also Read: