Nested WHILE loops in Python

≡放荡痞女 提交于 2019-12-09 18:20:38

问题


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
>>> b=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.


回答1:


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.



来源:https://stackoverflow.com/questions/2841489/nested-while-loops-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!