In this tutorial we will see two Python programs to swap two numbers. In the first program we are swapping the numbers using temporary variable and in the second program we are swapping without using temporary variable.
Program 1: Swapping two numbers using temporary variable
In this program we are using a temporary variable temp
to swap the two numbers. We are storing the value of num1
in temp
so that when the value of num1
is overwritten by num2
we have the backup of the num1
value, which we later assign to the num2.
# Program published on https://beginnersbook.com # Python program to swap two variables num1 = input('Enter First Number: ') num2 = input('Enter Second Number: ') print("Value of num1 before swapping: ", num1) print("Value of num2 before swapping: ", num2) # swapping two numbers using temporary variable temp = num1 num1 = num2 num2 = temp print("Value of num1 after swapping: ", num1) print("Value of num2 after swapping: ", num2)
Output:
Enter First Number: 101 Enter Second Number: 99 Value of num1 before swapping: 101 Value of num2 before swapping: 99 Value of num1 after swapping: 99 Value of num2 after swapping: 101
Program 2: Swapping two numbers without using temporary variable
# Program published on https://beginnersbook.com # Python program to swap two variables num1 = input('Enter First Number: ') num2 = input('Enter Second Number: ') print("Value of num1 before swapping: ", num1) print("Value of num2 before swapping: ", num2) # swapping two numbers without using temporary variable num1, num2 = num2, num1 print("Value of num1 after swapping: ", num1) print("Value of num2 after swapping: ", num2)
Output:
Enter First Number: 101 Enter Second Number: 999 Value of num1 before swapping: 101 Value of num2 before swapping: 999 Value of num1 after swapping: 999 Value of num2 after swapping: 101
Related Python Examples:
1. Python program to reverse a string
2. Python program to check leap year
3. Python program to find the length of a string
4. Python program to find factorial
5. Python program to display Calendar
Leave a Reply