Python program to swap numbers using temporary variable

 

Problem Definition:

In this program, we will learn how to swap two numbers using a temporary variable.

Logic

First, read two numbers from the keyboard. Display the numbers before swapping. Then swap the numbers using a temporary variable. Then display the swapped numbers.

Steps (Algorithm):

Step 1: Read two numbers from standard input (keyboard).

Step 2: Print or display original numbers on standard output.

Step 3: In this step, we do the actual swapping of numbers.

Let, num1 be the first variable and num2 be the second variable. First, we store the value of the first variable into a temporary variable. Then the value of the first variable is stored in the second variable. Finally, the value of the temporary variable will be stored in the first variable.

Step 4: Display the swapped numbers.

Sample Input to the program:

Number 1 = 20

Number 2 = 30

Expected Output:

Number 1 = 30

Number 2 = 20

Program to swap two numbers using a temporary variable:

#Python program to swap numbers using temporary variable
num1 = int (input ("Enter the first number: "))
num2 = int (input ("Enter the second number: ")) 

#Print original number
print ("Before swapping")
print ("First number is : ", num1)
print ("First number is : ", num2) 

#Swapping using temporary variable
temp = num1
num2 = num1
num1 = temp

#Print Swapped number
print ("After swapping") 
print ("First number is : ", num1)
print ("First number is : ", num2) 

Output:

Before Swapping
Enter the first number: 20
Enter the second number: 30

After Swapping
First number is: 30
Second number is: 20

The above programs deal with how to swap two numbers using a temporary variable. For more such programs do visit this website regularly. Also, do my Facebook page for regular updates – Click here to follow my Facebook page

Leave a Comment

Your email address will not be published. Required fields are marked *