Swapping two variables in python | Python Bootcamp

Introduction

In this post, you will learn how to swap two variables in python and also below is the video format of the post, check it out ????????. In addition, we will see an example of swapping variables…

Video:

Swapping two variables in python

Swapping two variables in python is very easy, let me take an example so, that you will be more familiar with what is swapping two variables in python.

For eg:

Before swapping

a = 5

b = 100

After swapping

a = 100

b = 5

Our main aim is to swap a variable and get the end result like this one ☝

To swap any variable we need to equalize the values, which will be something like this, ????????

c = a

a = b

b = c

c is another variable and what exactly happening here is the value in c will be equal to a and the value in a will be equal to b and finally, the value in b will be equal to c.

At last, when you print the result the values must be swapped.

Example in swapping two varaibles

Try it ????????????

# Python program to swap two variables
x = 5
y = 10
# 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(x)
print(y)

Just run in your favourite IDE or any compiler and you must see the below result ????????

Swapping two variables

Now you could see we have entered our own value, if you wanna the user to input their own value then make sure you enter the input function which looks something like this and just keep on trying ????

# Python program to swap two variables
x = input("print the x value: ")
y = input("print the y value: ")
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print("a = " + x)
print("b = " + y)

The result will be something like this one ????????

Swapping two variables

Also Read: Variables in python

Also Read: Len function in python full tutorial