codescracker


python

Python Program to Swap Two Numbers



« Previous Program Next Program »


Swap Two Numbers in Python

To swap two numbers in python, you have to ask from user to enter value of two numbers to swap those two numbers using the third variable. Swapping of two number means placing the value of first variable to second variable and the value of second variable to the first variable just by using another temporary variable.

Python Programming Code to Swap Two Numbers

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

To swap two numbers in python, first store the value of the first number to a temporary variable say swap, then store the value of the second variable to the first variable, and finally store the value of the temporary variable say swap to the second variable as shown in the program given below:

# Python Program - Swap Two Numbers
		
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")

Here is the sample run of the above python program to show how to swap two numbers in python:

python swap two numbers

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:


« Previous Program Next Program »




Tools
Calculator

Quick Links
Signup - Login - Give Online Test