【发布时间】:2014-07-03 21:08:00
【问题描述】:
我是 Python 的初学者,我的教授在解释循环之间的差异方面做得很差。我想问这个社区 For 循环和 While 循环之间的区别。我查看了各种资源,但令我感到困惑的是 for 循环如何没有计数器将它们带回到开头,就像 while 循环一样: 我在 for() 循环中编写了以下代码,但我的目标是将其更改为 while 循环。代码不是重要的是如何将此代码更改为 While() 循环。
for r_ow in range(Height_box):
for c_col in range(Width_box):
gridpoint = box * row + column
if gridpoint in gridList:
box[r_ow][c_col] = "Inside Box"
else:
outsideBox = (CurrentBox(boxWidth,Boxedge))
ctr = 0
for Box_edges in Box:
if eval(Box(boxWidth,boxHeight,box_edges,box_point)):
if box_edge in gridList:
ctr += 1
Bow[r_ow][c_col] = str(int(box[r_ow][c_col]) + ctr)
到目前为止,我已经到了这样的地步,我认为这就是它应该看起来的样子,但现在我陷入了 CMD 无限循环。
row = 0
while r_ow < boxHeight:
column = 0
while c_col < boxWidth:
gridpoint = box * row + column
if gridpoint in gridList:
box[r_ow][c_ol] = "Inside Box"
else:
outsideBox = (CurrentBox(boxWidth,Boxedge))
ctr = 0
while ctr < Boxes:
if eval(Box(boxWidth,boxHeight,box_edges,box_point)):
if box_edge in gridList:
ctr += 1
Bow[r_ow][c_col] = str(int(box[r_ow][c_col]) + ctr)
column += 1
row += 1
return box
任何人都可以就如何将第一个代码格式化为 while loops() 提供一些建议吗?
非常感谢!!
【问题讨论】:
-
您的缩进错误:
column += 1必须在内部while循环内,row += 1必须在外部while循环内。由于不正确的缩进,column永远不会递增并且内部的while循环。 -
这不是对您的代码的修复,而是对标题/第一段中几乎与语言无关的问题的回答。 Python 中的
for循环实际上是for...each循环。它读取“对于 Y 中的每个 X”,并允许您访问 X 以读取或更改它。while循环读取“while X is True”并且本质上是无限的:它仅在状态以预定方式发生变化时停止执行。
标签: python python-2.7 if-statement for-loop while-loop