Write A Python Script To Sort A List Given By User

In this article let's take a list of numbers from the user, the program has to accept the list of numbers from the user and then sort the list of numbers into an ascending order.

Once the numbers are started we need to print them.

 

Write A Python Script To Sort A List Given By User

 



Write A Python Script To Sort A List Given By User

Let's take a new variable named as n to store the list length and then using the input function call ask a user to enter the number and then convert it into an integer.

let's take a empty list variable and using the follow as the user to enter the numbers present in the list.  use the input function call to accept the  list of numbers and then app and it to the empty list.

n = int(input("Enter List Length : "))
user_list = []
for _ in range(n):
   temp = int(input("Enter List Item (Integer) : "))
   user_list.append(temp)



Use the Bubble sort to sort the list of numbers that are accepted from the user. Use two for loops. The first for loop will iterate from 0 to n(list length) and the next for loop will iterate from 0 to the first for loop index.


Using the statement check the  list containing index is greater than the next index if so swap both the values.  this will sort the list of numbers in ascending order.

for index in range(n):
  for next in range(n - index - 1):
      if user_list[next] > user_list[next + 1]:
          user_list[next], user_list[next + 1] = user_list[next + 1], user_list[next]


for item in user_list:
   print(item, end=" ")






Python Script
======================

n = int(input("Enter List Length : "))
user_list = []
for _ in range(n):
   temp = int(input("Enter List Item (Integer) : "))
   user_list.append(temp)


for index in range(n):
  for next in range(n - index - 1):
      if user_list[next] > user_list[next + 1]:
          user_list[next], user_list[next + 1] = user_list[next + 1], user_list[next]


for item in user_list:
   print(item, end=" ")






Output
=============

Enter List Length : 5
Enter List Item (Integer) : 77
Enter List Item (Integer) : 55
Enter List Item (Integer) : 34
Enter List Item (Integer) : 90
Enter List Item (Integer) : 99
34 55 77 90 99





Conclusion
========================

Execute the above Python program by passing multiple integer values as an input to the program, note down the results.

Comment it down below if you have any suggestions to improve our Python program.

 

 




Post a Comment

0 Comments