首页 > 解决方案 > 为什么我的 while 命令不起作用?

问题描述

我不明白为什么我的代码停止工作print "start with 8"

为什么不将数字 8 与数字 5、8、12、18、22 进行比较?

#Sum of two lowest integers
numbers = [5,8,12,18,22]
keep_ans = []
limit = len(numbers)
for i in numbers:
    print("Start with "+str(i))
    run = 0
    check_in = 0
    Done = False #It's stop here, when i = 8
    while Done == False:
        if i <= numbers[check_in]:
            print("Compare "+str(i)+" with "+str(numbers[check_in])+" round:"+str(run))
            run += 1
            check_in += 1
        if run == limit-1:
            keep_ans.append(i)
            Done = True
ans = sum(keep_ans)
print(ans)

我的代码的输出:

Start with 5
Check 5 with 5 round:0
Check 5 with 8 round:1
Check 5 with 12 round:2
Check 5 with 18 round:3
Start with 8

标签: python

解决方案


您被困在while循环中,因为在第二次迭代中您没有输入第一个if- 条件,因此永远不会将 1 添加到runand check_in

要解决这个问题,您需要更改缩进:

while Done == False:
    if i <= numbers[check_in]:
        print("Compare "+str(i)+" with "+str(numbers[check_in])+" round:"+str(run))
    run += 1
    check_in += 1

这样,您的算法将终止。


推荐阅读