Table of Contents

Python Program to Swap Two Numbers

Example Description
By taking user input for two numbers, the program showcases how to efficiently exchange their values using tuple assignments

Introduction:

This Python program takes two numbers as input and swaps their values using tuple assignments. The program then displays the numbers before and after swapping.

Code:

#Program to swap two numbers 
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print("\nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("\nNumbers after swapping:")
print("First Number:",num1)
print("Second Number:",num2)

Logic:

  1. Prompt the user to enter the first number.
  2. Prompt the user to enter the second number.
  3. Print the numbers before swapping.
  4. Swap the values of the two numbers using tuple assignments.
  5. Print the numbers after swapping.

Output:

Enter the first number: 10
Enter the second number: 5
>>

>> Numbers before swapping:

>> First Number: 10

>> Second Number: 5

>>

>> Numbers after swapping:

>> First Number: 5

>> Second Number: 10