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

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read