Coders Packet

Python script to sort elements in Ascending or Descending order

By Omprakash Biswas

Here user inputs a list of integers or floats or strings along with sorting type. The program outputs the sorted list according to specified sorting type i.e. Ascending or Descending order

At first, the program asks the user to input the number of elements(n) to be sorted. Then it asks for the ith element then it appends the data into the list end. There is also an option to add more data to the list for ease of access.

Then it asks the user to choose a sorting type, 'a' for ascending and 'd' for descending.

Finally, the program outputs the sorted list with the specified sorting order.

Please note it will output the sorted list as a list of strings even if you give another datatype as python by default takes input as a string.

 

# Python script to sort elements in Ascending or Descending order

# User input for array/list length
num = int(input("How many number do you want to sort? "))
# Initialising python list
lst = []
# Grabbing user list
for i in range(num) :
    # Appending the user data to the end of the list
    # {} & format method is used for string formatting
    lst.append(input("Enter {}th value :".format(i+1)))
add_more = input("Do you want to add more? (y/n)")
if add_more == 'y' :
    extra = int(input("How many value(s) to add? "))
    for i in range(num,num+extra) :
        lst.append(input("Enter {}th value :".format(i+1)))

# Grabbing the order type
sort_type = input("Sorting type (Ascending[a]/Descending[d])? ")
if sort_type == 'd' :
    st = 1
else :
    st = 0
lst.sort(reverse = st)
print("Sorted List : ",lst)

 

Output:

Output

Download Complete Code

Comments

No comments yet