简体   繁体   中英

Sentinel Values sorted order and reverse sort

Here is my task:

  1. Sorted Order

Write a program that reads integers from the user and stores them in a list. Your program should continue reading until the user enters a 0 (this is known as a sentinel value – a special value that is used to terminate a loop). Then it should display all of the values entered by the user (except for the 0) in ascending order, with one value appearing on each line. Use either the sort method or the sorted function to sort the list.

  1. Reverse Sort

Write a program that reads integers from the user and stores them in a list. Use 0 as a sentinel value to mark the end of the input. After all the values have been read your program should display them (except for the 0) in descending order, with one value appearing on each line.

I have some code for taking values from the user and storing them in a list. Any help getting closer to completion would be greatly appreciated.

my_list=[]

while True:
    value = input("please enter a value:")
    if value :
        my_list.appent(value)
    else:
        break
print("value added")

for elem in my_list:
    print(f"\t(elem)")

you can use the python method: sorted :

my_list=[]

while True:
    value = input("please enter a value:")
    if value > 0:
        my_list.appent(value)
    else:
        break
print("value added")

sorted_list = sorted(my_list)
for elem in sorted_list:
    print(f"\t(elem)")

reverse_sorted_list = sorted(my_list, reverse=True)
for elem in reverse_sorted_list:
    print(f"\t(elem)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM