Python Program to Swap Two Variables Example

Python

Nicesnippets

434

15-06-2021


Python Program to Swap Two Variables Example

Hello Friend,

Today, I am going learn you how to swap two variables in python program. We will talk about python program to swap two variables. I would like to share with you how to swap two variable in python.

In this article, I will show swap two variable using third variable in python. We will teach swapping of two numbers in python with temporary variable.

Here i will give you three example of swapping of two numbers in python program. So let's see the bellow example:

Example 1


swap.py

# Python program to swap two variables

x = 15

y = 25

# create a temporary variable and swap the values

temp = x

x = y

y = temp

print('The value of x after swapping: {}'.format(x))

print('The value of y after swapping: {}'.format(y))

Output :

The value of x after swapping: 25

The value of y after swapping: 15

Example 2

swap.py

# To take inputs from the user

x = input('Enter value of x: ')

y = input('Enter value of y: ')

# create a temporary variable and swap the values

temp = x

x = y

y = temp

print('The value of x after swapping: {}'.format(x))

print('The value of y after swapping: {}'.format(y))

Output :

Enter value of x: 5

Enter value of y: 10

The value of x after swapping: 10

The value of y after swapping: 5

Example 3 : Without Using Temporary Variable

swap.py

# To take inputs from the user

x = input('Enter value of x: ')

y = input('Enter value of y: ')

# swap the values without temporary variable

x, y = y, x

print('The value of x after swapping: {}'.format(x))

print('The value of y after swapping: {}'.format(y))

Output :

Enter value of x: 55

Enter value of y: 60

The value of x after swapping: 60

The value of y after swapping: 55

Run python file:

python swap.py

It will help you....


Recommended Posts