为什么我的蟒蛇在循环不起作用时嵌套了?

发布于 2025-02-11 10:33:44 字数 376 浏览 0 评论 0原文

我正在学习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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奢欲 2025-02-18 10:33:44

这是因为循环无法测试sum值,直到内部循环完全完成为止。您将需要类似的东西:

for n in numbers:
   sum += n
   if sum >= 10:
      break

至于第二个样本,请跟踪它:

for n in numbers:
 while sum < 10:
  sum += n

首先,n将设置为4。然后,您在内部环中停留一段时间。 sum将变为4,然后是8,然后是12,然后将其退出。随着外循环通过其余数字,sum已经大于10,因此循环永远不会运行。

您不能使用两个嵌套循环来完成任务。它必须是一个具有额外退出条件的循环。

It's because the outer while loop cannot test the sum value until the inner loop has totally completed. You would need something like this:

for n in numbers:
   sum += n
   if sum >= 10:
      break

As for your second sample, trace through it:

for n in numbers:
 while sum < 10:
  sum += n

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 the while loop never runs.

You can't use two nested loops to accomplish your task. It must be one loop with an extra exit condition.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文