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.
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 = b
b = temp
# 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.
0 Comments