Python Program to python program to swap two variables

February 16, 2022, Learn eTutorial

In this simple python program, we need to swap the numbers using a temporary variable. It's a beginner-level python program.

To understand this example, you should have knowledge of the following Python programming topics:

How to swap the variables in python?

Here in this python program example is for beginners; we are swapping two variables to each other using a temporary variable. For example, if x=a and y=b then we do the swap, and the result will be x=b and y=a. This is a simple logic to swap using a temporary variable.

To apply this logic in the python programming language, we have to use a temporary variable. This temporary variable to store the value of x and we apply the value of y to x and then apply the value of temp to y. temp = x, x = y, y = temp Now we break the code step by step.


STEP 1: Accept the user input using the function input in the simple python program and store that value to a variable.

STEP 2: Create a temporary variable temp and swap the value of x to temp.

STEP 3: Swap the value of y to x and then swap the value of temp to y.

STEP 4: Print the value of x and y after swapping using the format method.

The format method is described in the quadratic equation python program.

Python Source Code

                                          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('after swapping the X is: {}'.format(x))  
print('after swapping the Y is: {}'.format(y))  


Enter value of x: a
Enter value of y: b

after swapping the X is: b
after swapping the y is: a