How to Exchange Two numbers’ Values in Python


In this example, we will learn how to exchange the values of two numbers. In Python, there are two solutions:

(1) using the method of addition/subject to complete the exchange;

(2) using a temporary viable as a carrier to realize the two numbers’ transfer.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

#Method 1
i = int(input("Please input the first value: "))
j = int(input("Please input the second value: "))
i = i + j
j = i - j
i = i - j
print("The first value changes to {} and the second value changes to {}.".format(i, j))

#Method 2
i = int(input("Please input the first value: "))
j = int(input("Please input the second value: "))
k = i
i = j
j = k
print("The first value changes to {} and the second value changes to {}.".format(i, j))

Output:

Please input the first value: 10
Please input the second value: 15
The first value changes to 15 and the second value changes to 10.
Please input the first value: 10
Please input the second value: 15
The first value changes to 15 and the second value changes to 10.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement