# Python Program to Swap Two Numbers

You are Here:

## Python Program to Swap Two Numbers

In programming, there are two different techniques to swap any two numbers in a variable, they are

• Swap using Temporary Variable
• Swap without using Temporary Variable

## Swap using Temporary Variable

In the following example, we will swap two numbers (25 and 50) using a temporary variable (temp).

### Example

Python Compiler
num1 = 25; num2 = 50; temp = 0; temp = num1; num1 = num2; num2 = temp; print("After swapping...") print("num1 = %d" % (num1)) print("num2 = %d" % (num2))

### Output

After swapping... num1 = 50 num2 = 25

## Swap without using Temporary Variable

In the following example, we will swap two numbers (25 and 50) without using a temporary variable.

### Example

Python Compiler
num1 = 25; num2 = 50; num1 = num1 - num2; num2 = num1 + num2; num1 = num2 - num1; print("After swapping...") print("num1 = %d" % (num1)) print("num2 = %d" % (num2))

### Output

After swapping... num1 = 50 num2 = 25

## Swap any Two Given Numbers

In the following example, we will swap any two given numbers without using a temporary variable (temp).

### Example

Python Compiler
num1 = int(input("Enter a (int) Number1: ")); num2 = int(input("Enter a (int) Number2: ")); num1 = num1 - num2; num2 = num1 + num2; num1 = num2 - num1; print("\nAfter swapping...") print("num1 = %d" % (num1)) print("num2 = %d" % (num2))

### Output

Enter a (int) Number1: 15 Enter a (int) Number2: 30 After swapping... num1 = 30 num2 = 15

## Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Python with examples for quick and easy learning.

We are working to cover every Single Concept in Python.