Python Program to Swap Two Variables

219
views
Swap Two Variables

In this program, you’ll learn how to Swap Two Variables in Python.

To properly understand this how to Swap Two Variables, you should have the knowledge of following Python programming topics:

  1. Python Input, Output and Import
  2. Python Variables and Data Types
  3. Python Operators

Program to Swap Two Variables Using temporary variable

# Python program to swap two variables

# To take input from the user
# x = input('Enter value of x: ')
# y = input('Enter value of y: ')

x = 5
y = 10

# 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: 10
The value of y after swapping: 5

Python Program to Swap Two Variables

In the above program the temp variable to temporarily hold the value of x. We then put the value of y in x and later temp in y. This is how values get exchanged.

Program to Swap Two Variables without Using temporary variable

There is a simple construct to swap the variables in Python, the code below will do the same as above code.

x,y = y,x

If the variables are both numbers, we can use arithmetic operations to do the same. It might not look intuitive at the first sight. But if you think about it, it’s pretty easy to figure it out.Here are a few examples

Addition and Subtraction
x = x + y
y = x - y
x = x - y
Multiplication and Division
x = x * y
y = x / y
x = x / y
XOR swap

This algorithm works for integers only

x = x ^ y
y = x ^ y
x = x ^ y

Related Examples:

  1. Addition of Two Numbers Given by User in Python
  2. Program to find the area of Triangle in Python
  3. Program to Solve Quadratic Equation in Python
  4. Program to Generate a Random Number in Python
  5. Program to Generate a Random alphanumeric String in Python

Ask your questions and clarify your/others doubts on how to Swap Two Variables in Python by commenting. Python Documentation