Python Program to Swap Two Numbers

1 min read

Problem Definition

Create a Python program to swap two numbers taking runtime inputs. Swapping means interchanging, for instance, say we have two variables holding the following values a = 10 & b = 20 after swapping they will interchange the values so now a = 20 & b = 10.

Solution

Generally, a third variable is used for swapping where first we store the value of the first variable to a temporary variable say temp, then store the value of the second variable to the first variable and finally, store the value of the temporary variable to the second variable.

Fortunately, Python comes with a simple built-in method to swap two numbers without using any third variable.

 a,b = b,a

This one-liner can swap values of two variable without using any additional variable, let's see this in action in the program below.

Algorithm

  1. Take input from the user and store them in variables
  2. Print the values before swapping
  3. Print the values after swapping
  4. End

Program

num1 = input('Enter First Number: ')
num2 = input('Enter Second Number: ')

print("Value of num1 before swapping: ", num1)
print("Value of num2 before swapping: ", num2)

num1, num2 = num2, num1

print("Value of num1 after swapping: ", num1)
print("Value of num2 after swapping: ", num2)

Runtime Test Cases

Enter First Number: 2
Enter Second Number: 3
Value of num1 before swapping:  2
Value of num2 before swapping:  3
Value of num1 after swapping:  3
Value of num2 after swapping:  2

The values inside the variables are interchanged; hence we swapped two numbers without using any third variable in Python.


PROGRAMS

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read