How to Swap Numbers in Python


Here this example focuses on how to swap numbers in Python.

Source Code

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

n1 = int(input('n1 = '))
n2 = int(input('n2 = '))
n3 = int(input('n3 = '))

def swap(p1, p2):
    return p2, p1

if n1 > n2: n1, n2 = swap(n1, n2)
if n1 > n3: n1, n3 = swap(n1, n3)
if n2 > n3: n2, n3 = swap(n2, n3)

print('Sorting results:');
print(n1, n2, n3)

Output:

n1 = 123
n2 = 321
n3 = 444
Sorting Results:
123 321 444
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement