In this post, you will learn how to write a python program to swap two numbers with a detailed explanation and example but first, let us see how many different ways to do this program.

There are three different ways to write a python program to swap two numbers and those are:

  1. Using the third Variable.
  2. Without using the third Variable &
  3. pythonic ways (Python gives you the flexibility to swap two numbers very easily)

NOTE: You can use the logic of the first two approaches in any programming language, but the third one is only applicable in the python programming language.

Using the third Variable

Before writing a program few programming concepts you have to know:

  1. Python operators
  2. python Data types &
  3. Variables in python

Source Code

# Using third variable

a = 7
b = 5
print('before swapping')
print('a =',a)
print('b =',b)

# taking third Variable 'c'
c = a
a = b
b = c

print('After swapping')
print('a =',a)
print('b =',b)

Output

before swapping
a = 7
b = 5
After swapping
a = 5
b = 7

Here Variable c act as a container and with the help of Variable c we swap a & b.

Without Using the third Variable

Before writing a program few programming concepts you have to know:

  1. Python operators
  2. python Data types &
  3. Variables in python

Source Code

# Without Using third Variable

a = 3
b = 9
print('before swapping')
print('a =',a)
print('b =',b)

a = a + b  
b = a - b 
a = a - b  

print('After swapping')
print('a =',a)
print('b =',b)

Output

before swapping
a = 3
b = 9
After swapping
a = 9
b = 3

Pythonic way to Swap Two Numbers

In python, it is very easy to swap two numbers as compared to any other programming language.

Source Code

# Pythonic way

a = 2
b = 8
print('before swapping')
print('a =',a)
print('b =',b)

a,b = b,a

print('After swapping')
print('a =',a)
print('b =',b)

Output

before swapping
a = 2
b = 8
After swapping
a = 8
b = 2

In a Pythonic way, we do a,b = b,a and it will swap a & b.

Related Topic:

5 Different ways to swap two numbers in python.

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment