Friday, May 17, 2019

Abhijeet Pal: Python Program to Swap Two Numbers

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.

The post Python Program to Swap Two Numbers appeared first on Django Central.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...