22.4 C
New York
Wednesday, February 21, 2024
HomeProgrammingPythonPython 3 Program To Swap Two Numbers

Python 3 Program To Swap Two Numbers

Here you will find the Python 3 program to swap two numbers with and without using third variable. Download source code of file from GitHub.

Here, you will find the Python 3 program to swap two numbers. Before starting, you should know basic Python concepts such as data types, variables, and operators. Also, check out these best Python books to learn Python more comprehensively.

Also ReadSending Emails Using Python With Image And PDF Attachments.

Python 3 program to swap two numbers using a third variable

Here, we will use a temporary variable (XYZ) to swap two numbers (firstNum and secondNum).

We will first store the value of firstNum in XYZ and then save the value of secondNum in firstNum.

At last, we will save the value of XYZ to secondNum. In this way, two numbers are swapped using a temporary variable.

firstNum = input("Enter first number = ")
secondNum = input("Enter second number = ")
print("First Number = ", firstNum)
print("Second Number = ", secondNum)
print("After swapping using a temp variable")

#code to swap two numbers using a third variable

xyz = firstNum
firstNum = secondNum
secondNum = xyz

print("First Number Now = ", firstNum)
print("Second Number Now = ", secondNum)

Output

python program to swap two numbers using third variable

Python 3 program to swap two numbers without using a third variable

There is a simple construct to swap variables in Python. The code below does the same.

firstNum = input("Enter first number = ")
secondNum = input("Enter second number = ")
print("First Number = ", firstNum)
print("Second Number = ", secondNum)

#Code to swap two numbers without any third variable

firstNum, secondNum = secondNum, firstNum
print("After swapping without using a temp variable")
print("First Number Now = ", firstNum)
print("Second Number Now = ", secondNum)

Output

python program to swap two numbers without using third variable

Related Python 3 Examples

  1. How To Make A Simple Python Calculator Using Functions.
  2. Python 3 Program to Calculate The Area of a Triangle.
Himanshu Tyagi
Himanshu Tyagi
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator. With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
RELATED ARTICLES
0
Would love your thoughts, please comment.x
()
x