Python中嵌套的WHILE循环

Gur*_*uru 5 python for-loop while-loop nested-loops

我是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
Run Code Online (Sandbox Code Playgroud)

我期待外循环遍历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
Run Code Online (Sandbox Code Playgroud)

但是,WHILE循环有什么问题?我想我错过了一些显而易见的事情,但无法理解.

答案: 纠正的WHILE循环..

>>> 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
Run Code Online (Sandbox Code Playgroud)

PS:搜索出SO,发现几个问题,但没有一个接近这个.不知道这是否可以归类为家庭作业,实际的程序是不同的,问题是困扰我的.

Ale*_*lli 7

你没有b在你的外循环内部重置为0,所以b保持在外循环的第一段之后的值 - 4 - 并且内循环永远不会再次执行.

for回路正常工作,因为他们正确重置其循环控制变量; 使用结构较少的while循环,这样的重置就在你手中,而你却没有这样做.