How to Sort Numbers with Swap in Python


In this example, we will learn how to rank three numbers in Python.

Source Code

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

a = [input("please input your first num:"),input("please input your second num:"),input("please input your third num:")]

def swap(i,j):
    temp = a[i]
    a[i] = a[j]
    a[j] = temp
for k in range(0,3):
    for m in range(0,3):
        if int(a[k])<int(a[m]):
            swap(k,m)

# Output results
print('\nSorted list:')
print(a)

Output:

please input your first num: 23
please input your second num: 12
please input your third num: 19

Sorted list:
['12', '19', '23']
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments