python - 为什么我的 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
解决方案
您被困在while
循环中,因为在第二次迭代中您没有输入第一个if
- 条件,因此永远不会将 1 添加到run
and 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
这样,您的算法将终止。
推荐阅读
- linux - 如何在 linux redhat 中列出池?
- angular2-nativescript - 任何人都可以帮助我提供一些指导以使用 Nativescript 在滚动视图中实现固定标题/粘性标题
- django - 创建发送邮件的基本联系表单
- javascript - 为什么当 Js 处于活动状态时我的表单只能在 chrome 中工作?
- php - 在 AJAX 中的 POST 请求后,此请求没有可用的响应数据
- matlab - 维纳滤波器通过相同大小的卷积对模糊图像失败
- python - 完整的 IPv4 地址空间输出
- c# - C# Async Await 和一般异步问题
- javascript - 如何正确使用 .click 在 Javascript 中的 html 编码中选择此类型?
- azure - Azure 认知服务可以与本地模型一起使用吗?