► Python program to swap two numbers using temp variable

Steps followed:
1. take input from user and store in num1 and num2 variables
2. validate user input by converting to integer
3. store num1 value in temp
4. copy num2 value in num1
5. now copy temp value in num2
6. print values


#python program to swap two numbers using temp variable

#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
    print("you have entered valid numbers")    
    #store num1 value in temp
    temp = num1

    #copy num2 value in num1
    num1 = num2

    #now copy temp value in num2
    num2 = temp

    #print result
    print("num1 value is %d"%(num1))
    print("num2 value is %d"%(num2))
    print("you have entered an invalid number")


Enter value for num1: 27
Enter value for num2: 79
you have entered valid numbers
num1 value is 79
num2 value is 27


Enter value for num1: 65
Enter value for num2: ls
you have entered an invalid number

Also Read: