Algorithm


Input:
     Take input for variable a.
     Take input for variable b.

Swap Variables:
     Use a temporary variable to store the value of a.
     Assign the value of b to a.
     Assign the value stored in the temporary variable to b.

Output:
     Print the values of a and b after swapping.

Code Examples

#1 Using a temporary variable

Code - Python Programming

# 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('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
Copy The Code & Try With Live Editor

Output

x
+
cmd
The value of x after swapping: 10
The value of y after swapping: 5

#2 Without Using Temporary Variable

Code - Python Programming

x = 5
y = 10

x, y = y, x
print("x =", x)
print("y =", y)
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Python Programing Example to Swap Two Variables-DevsEnv