python中自带排序函数的无限循环

时间:2016-06-18 18:36:19

标签: python loops

我是python的新手,作为excersize,我想用我对python的一点知识来编写排序函数。但我的代码以无限循环结束,但我无法弄清楚原因。有人可以帮忙吗?

这是我的代码

#create list
sezn = []
while True:
    try :
        a = int(input("Number: "))
        sezn.append(a)
    except :
        break
#print min, max and mean
print (sezn)
print("minimum: ", min(sezn))
print ("maximum: ", max(sezn))
fin = 0
for i in sezn:
    fin += i
mean = fin/len(sezn)
print ("mean: ", mean)
#sorting function    
sort = []
sez = []
index = 0
length = len(sezn)
print (length)
while index < length:
    for i in sezn:
        if i == min(sezn):
            sort.append(i)
        else:
            sez.append(i)
    index += 1
    sezn = sez
print(sort)

2 个答案:

答案 0 :(得分:0)

您忘记在while循环期间将sez设置为空列表:

while index < length:
    sez = [] # <-- need to add this line, and you can also get rid of this from before the while loop
    for i in sezn:
        if i == min(sezn):
            sort.append(i)
        else:
            sez.append(i)
    index += 1
    sezn = sez

答案 1 :(得分:0)

循环是无限的,因为你没有离开它。

如果你只是想要离开循环。然后:

sezn = []
while True:
    try :
        a = int(input("Number: "))
        sezn.append(a)
        break
    except :
    break