by BehindJava

Write a program to swap two numbers in Python

Home » python » Write a program to swap two numbers in Python

In this tutorial we are going to learn about swapping two numbers in Python.

Swapping Two Numbers

Method 1:

# Python swap program   
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))  

The common approach is to store the value of one variable(say x) in a temporary variable, then assigning the variable x with the value of variable y. Finally, assign the variable y with the value of the temporary variable.

Method2:

Using comma operator .Using the comma operator the value of variables can be swapped without using a third variable.

**Swapping of two variables
without using third variable** 
 
x = 10
y = 50
 

x, y = y, x
 
print("Value of x:", x)
print("Value of y:", y)