猿问

用户输入以降序排列输出

用户输入,其中输出将按降序排序。


例如,输入一个数字:


你想输入更多:


如果是打印输入另一个数字


如果回答否


打破argument并按降序对输出进行排序。


我已经用于raw_input查询和使用while 循环来运行代码。但它仅按降序对第一个输出和最后一个输出进行排序


a = raw_input("Enter a number: ")

while True:

    b = raw_input("Do you want to input more: ")

    c = raw_input("Enter another number:")

    if b == 'yes':

        print (c)

        continue

    elif b == 'no':

        my_list = [a,c]

        my_list.sort(reverse=True)

        print(my_list)

        break

我希望代码能够成功运行


Enter a number:2

Do you want to input more:yes

Enter another number:3

Do you want to input more:yes

Enter another number:4

Do you want to input more:no

[4,3,2]


狐的传说
浏览 217回答 3
3回答

元芳怎么了

在Python 3.x 中,使用input()代替raw_input()创建一个list将用户输入附加到其中,以便稍后对其进行排序。input_List = []input_List.append(int(input("Enter a number: ")))while True:    b = input("Do you want to input more: ")    if b == 'yes':        input_List.append(int(input("Enter a number: ")))    elif b == 'no':        input_List.sort(reverse=True)        breakprint(input_List)输出:Enter a number: 5Do you want to input more: yesEnter a number: 7Do you want to input more: yesEnter a number: 90Do you want to input more: no[90, 7, 5]

LEATH

它应该是这样的:a = input("Enter a number: ")l = [int(a)]while True:    b = input("Do you want to input more: ")    if b == 'yes':        c = input("Enter another number:")        l.append(int(c))    elif b == 'no':        l.sort(reverse=True)        print(l)        break

慕仙森

很多逻辑错误,还有更微妙的错误raw_input 返回一个字符串,除非您转换为整数,否则您将无法获得正确的数字排序。是/否问题逻辑被打破,来得太晚了......你永远不会append在你的列表中使用,它总是包含 2 个元素。my_list = [a,c]没有意义。我的建议:# this is for retrocompatibility. Python 3 users will ditch raw_input altogethertry:    raw_inputexcept NameError:    raw_input = input   # for python 3 users :)# initialize the list with the first elementmy_list = [int(raw_input("Enter a number: "))]while True:    b = raw_input("Do you want to input more: ")    if b == 'yes':        # add one element        my_list.append(int(raw_input("Enter another number:")))    elif b == 'no':        my_list.sort(reverse=True)        print(my_list)        break
随时随地看视频慕课网APP

相关分类

Python
我要回答