为什么我的蟒蛇在循环不起作用时嵌套了?
我正在学习python,很难理解这个嵌套循环中我的逻辑有什么问题。
numbers = [4, 3, 1, 3, 5]
sum = 0
while sum < 10:
for n in numbers:
sum += n
print(sum)
虽然总和小于10,但通过列表中的下一个对象迭代并将其添加到总和中。因此,它应该打印11(4+3+1+3,然后停止),而是打印16。我尝试更改循环顺序:
for n in numbers:
while sum < 10:
sum += n
但是它打印了12个,这进一步使我感到困惑。
有人可以帮忙吗?谢谢你!
I'm learning Python and have a hard time understanding what's wrong with my logic in this nested loop.
numbers = [4, 3, 1, 3, 5]
sum = 0
while sum < 10:
for n in numbers:
sum += n
print(sum)
While sum is less than 10, iterate through the next object in a list and add it to the sum. Thus, it's supposed to print 11 (4+3+1+3, then it stops), but instead it prints 16. I have tried changing the order of loops:
for n in numbers:
while sum < 10:
sum += n
But then it prints 12, which further confuses me.
Can anybody please help? Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为循环无法测试
sum
值,直到内部循环完全完成为止。您将需要类似的东西:至于第二个样本,请跟踪它:
首先,
n
将设置为4。然后,您在内部环中停留一段时间。sum
将变为4,然后是8,然后是12,然后将其退出。随着外循环通过其余数字,sum
已经大于10,因此循环永远不会运行。
您不能使用两个嵌套循环来完成任务。它必须是一个具有额外退出条件的循环。
It's because the outer
while
loop cannot test thesum
value until the inner loop has totally completed. You would need something like this:As for your second sample, trace through it:
To start with,
n
will be set to 4. You then stay in the inner loop for a while.sum
will become 4, then 8, then 12, then that loop exits. As the outer loop goes through the rest of the numbers,sum
is already greater than 10, so thewhile
loop never runs.You can't use two nested loops to accomplish your task. It must be one loop with an extra exit condition.