python - Having user sort list smallest to biggest -


so i'm making code asks user to swap 2 places on list until list smallest biggest. should this:

hello:  current list [6, 7, 8, 2 , 9, 10, 12, 15, 16, 17] please pick first location ->   4 please pick second location ->  2 new list [6, 2, 8, 7 , 9, 10, 12, 15, 16, 17] 

i've gotten part unable figure out how user sorting , not code.

your list not sorted: please continue please pick first location ->   1 please pick second location ->  2  new list [2, 6, 8, 7 , 9, 10, 12, 15, 16, 17] please pick first location ->   3 please pick second location ->  4  new list [2, 6, 7, 8 , 9, 10, 12, 15, 16, 17]  great job, thank sorting list. 

here code:

list = [4,2,5,5,6,4,7,6,9,5] print("heres current list", list)  print("pick location between 1 , 10") num = int(input()) if num <= 10 , num >= 1:     print("please pick location between 1 , 10")     num1 = int(input())     tempbox1 = list[num-1]     tempbox2 = list[num1-1]     list[num-1] = tempbox2     list[num1-1] = tempbox1     print("your new list is", list) 

from understand confusing explanation, made working script coding conducts every beginner should learn when starting python , programming overall. 2 first small functions used avoid code repetition, way can avoid aswell long main function code.

also, last condition happens when run python script (you can find better explanation here).

# function avoid code repetition def verify_index(number):     return 1 <= number <= 10  # function ask number indexes until fit list length def input_numbers():     while true:         num1 = int(input("pick location between 1 , 10: "))         num2 = int(input("please pick location between 1 , 10: "))         if verify_index(num1) , verify_index(num2):             return num1, num2  # list , variables defined locally here def main_function():     list = [2, 4, 5, 5, 5, 5, 5, 5, 9, 5]     print("heres current list", list)     num1, num2 = input_numbers()     while true:         print(num1,num2)         temp = list[num1-1]         list[num1-1] = list[num2-1]         list[num2-1] = temp         print("your new list now: ", list)         if list == sorted(list):             break         num1, num2 = input_numbers()     print("congratulations! list sorted commands!")  # code script execute once run if __name__ == '__main__':     main_function() 

any question or doubt, feel free ask.

(edit: fixing verify_index function better pattern, suggestion user tesselatinghecker)


Comments