write a program to swap two numbers using third variable

Hi, in this article let's look into swapping two numbers using a third variable.

Given two numbers from the user, you have to swap the values present in these two numbers using the third variable so let's ask the user to enter two numbers and then swap the variables using the third variable.  

 

Write a Program to Swap Two Numbers Without Using Third Variable in Python

 



Just use a temporary variable to store the first number then assign the second number to the first variable and then assign temp value to the second variable,  as shown below

temp = a
a = b
b = temp

Once we execute the above  three statements the numbers present in both the variables will be swapped successfully.


Python Program to Swap Two Numbers Using Third Variable

Take two variables a and b and ask the user to enter two numbers and then convert the type from string to integer using int() function call. Once we get two numbers let's take another variable temp and swap the numbers  as shown above. 

a = int(input("Enter First Number : "))
b = int(input("Enter Second Number : "))
 
temp = a
a = b
b = temp
 
print("Value of First Variable is : ", a)
print("Value of Second Variable is : ", b)
 
 
OUTPUT : 

# python main.py
Enter First Number : 10
Enter Second Number : 20
Value of First Variable is :  20
Value of Second Variable is :  10


Conclusion : Try the program by yourself and comment down below if any queries / suggestions.

Post a Comment

0 Comments