Python 中的嵌套 WHILE 循环

发布于 2024-09-01 20:31:55 字数 944 浏览 4 评论 0原文

我是 Python 初学者,尝试了一些程序。我在 Python 中有类似下面的 WHILE 循环构造(不准确)。

IDLE 2.6.4      
>>> a=0
>>> b=0
>>> while a < 4:
      a=a+1
      while b < 4:
         b=b+1
         print a, b

  
1 1
1 2
1 3
1 4

我期望外层循环遍历 1、2、3 和 4。我知道我可以像这样使用 FOR 循环来做到这一点

>>> for a in range(1,5):
       for b in range(1,5):
           print a,b

  
1 1
1 2
.. ..
.. .. // Other lines omitted for brevity
4 4

但是,WHILE 循环有什么问题?我想我错过了一些明显的事情,但无法弄清楚。

答案: 更正的 WHILE 循环..

>>> a=0
>>> while a < 4:
    a=a+1
    b=0
    while b<4:
        b=b+1
        print a,b

        
1 1
.. ..
.. .. // Other lines omitted for brevity
4 4

PS:搜索了 SO,发现 几个问题 但没有一个与此接近。不知道这是否可以归为作业,实际程序不同,问题是我困惑的地方。

I am a beginner with Python and trying few programs. I have something like the following WHILE loop construct in Python (not exact).

IDLE 2.6.4      
>>> a=0
>>> b=0
>>> while a < 4:
      a=a+1
      while b < 4:
         b=b+1
         print a, b

  
1 1
1 2
1 3
1 4

I am expecting the outer loop to loop through 1,2,3 and 4. And I know I can do this with FOR loop like this

>>> for a in range(1,5):
       for b in range(1,5):
           print a,b

  
1 1
1 2
.. ..
.. .. // Other lines omitted for brevity
4 4

But, what is wrong with WHILE loop? I guess I am missing some thing obvious, but could not make out.

Answer:
The corrected WHILE loop..

>>> a=0
>>> while a < 4:
    a=a+1
    b=0
    while b<4:
        b=b+1
        print a,b

        
1 1
.. ..
.. .. // Other lines omitted for brevity
4 4

P.S: Searched out SO, found few questions but none as close to this. Don't know whether this could classified as homework, the actual program was different, the problem is what puzzles me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

夏见 2024-09-08 20:31:55

您没有在外循环内将 b 重置为 0,因此 b 保持在外循环第一段之后的值 - 4 - 并且内部循环永远不会再执行。

for 循环工作得很好,因为它们确实正确地重置了循环控制变量;对于结构较少的 while 循环,这种重置是在你的手中,而你却没有这样做。

You're not resetting b to 0 right inside your outer loop, so b stays at the value it had after the first leg of the outer loop -- 4 -- and the inner loop never executes again.

The for loops work fine because they do reset their loop control variables correctly; with the less-structured while loops, such resetting is in your hands, and you're not doing it.

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