How to Swap Two Numbers in Python?

01-Nov-2022

.

Admin

How to Swap Two Numbers in Python?

Hi Dev,

This post is focused on How to Swap Two Numbers in Python. I explained simply about Swapping of Two Numbers in Python. it's simple example of Python program to swap two numbers without using third variable. In this article, we will implement a Python Program To Swap Two Numbers. you will do the following things for Write a Program to Swap two Numbers Using Python.

Python program to swap two numbers; Through this tutorial, you will learn how to swap two numbers with and without third variable in python.

so let's see following examples with output:

Example 1: Python program to swap two numbers using the temporary /third variable


# Python program to swap two variables using temp variable

num1 = input('Enter First Number: ')

num2 = input('Enter Second Number: ')

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

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

# swapping two numbers using temporary variable

temp = num1

num1 = num2

num2 = temp

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

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

Output:

Enter First Number: 5

Enter Second Number: 6

Value of num1 before swapping: 5

Value of num2 before swapping: 6

Value of num1 after swapping: 6

Value of num2 after swapping: 5

Example 2: Python program to swap two numbers without using the temporary /third variable

# Python program to swap two variables without using third varible

num1 = input('Enter First Number: ')

num2 = input('Enter Second Number: ')

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

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

# swapping two numbers without using temporary variable

num1, num2 = num2, num1

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

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

Output:

Enter First Number: 9

Enter Second Number: 8

Value of num1 before swapping: 9

Value of num2 before swapping: 8

Value of num1 after swapping: 8

Value of num2 after swapping: 9

I hope it can help you...

#Python