BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Python Program to Swap Two Numbers

Last Updated: June 8, 2018 by Chaitanya Singh | Filed Under: Python Examples

In this tutorial we will see two Python programs to swap two numbers. In the first program we are swapping the numbers using temporary variable and in the second program we are swapping without using temporary variable.

Program 1: Swapping two numbers using temporary variable

In this program we are using a temporary variable temp to swap the two numbers. We are storing the value of num1 in temp so that when the value of num1 is overwritten by num2 we have the backup of the num1 value, which we later assign to the num2.

# Program published on https://beginnersbook.com

# Python program to swap two variables

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: 101
Enter Second Number: 99
Value of num1 before swapping:  101
Value of num2 before swapping:  99
Value of num1 after swapping:  99
Value of num2 after swapping:  101