Signup/Sign In
PUBLISHED ON: FEBRUARY 15, 2022

Python program to swap two numbers using third variable

learn python language tutorial

In this article, you will learn to write a python program that will swap the numbers using a third variable. Here, we will take temp as the third variable such that we will use the temp variable to temporarily store the first number's value.

As the output, we are required to get the swapped numbers.

Look at the given example to understand the working with input and output.

Input:

num1=8

num2=13

Output:

num1=13

num2=8

Let us take one more example-

Input:

num1=8

num2=13

Output:

num1=13

num2=8

Algorithm

Step 1: Define a new variable "temp" to store the values temporarily.

Step 2: Store the value of num1 in temp.

Step 3: Assign the value of the second number (num2) to the num1.

Step 4: Now as the value of num1 is exchanged with the first number, finally assign the temp value to num 2.

Python Program

Look at the complete program given below to understand the implementation of the approach.

#program to swap two numbers using third variable

#Input
num1 = input('Enter value of first number (num1): ')
num2 = input('Enter value of second number (num2): ')

# create a temporary variable and swap the values
temp = num1
num1 = num2
num2 = temp

#Output
print('The value of num1 after swapping: {}'.format(num1))
print('The value of num2 after swapping: {}'.format(num2))


Enter value of first number (num1): 6
Enter value of second number (num2): 3
The value of num1 after swapping: 3
The value of num2 after swapping: 6

The format() is a function for handling strings that permits you to do variable substitutions and data formatting. Here we have used this function to print the value of numbers. This function will print the value where {} is present.

Conclusion

In this tutorial, we have seen how to swap two given numbers using a third variable temp which is used to stores the values temporarily.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.