【问题标题】:nested loop not working嵌套循环不起作用
【发布时间】:2014-02-21 17:05:00
【问题描述】:

谁能告诉我为什么这个嵌套循环只执行一次内部while部分而不是8次?

corCols = 10
corRows = 8
cCount = 0
for rCount in range(corRows):
    while cCount < corCols:
        print "***" + str(cCount)
        cCount += 1
    print "###" + str(rCount)

这会通过列打印第一次迭代,然后通过行打印迭代,但似乎只执行一次 while 部分?

【问题讨论】:

  • 运行了10次,for循环第一次运行。
  • 你的意思是问为什么没有运行 80 次?
  • cCount 不再小于 corCols。顺便说一句,那里有一些严肃的标识符名称。

标签: python loops nested


【解决方案1】:

你需要在内部循环之前将 cCount 重置为零

【讨论】:

    【解决方案2】:

    你的内部循环只运行一次,因为cCountfor 循环第一次迭代时递增到10。此后cCount 停留10 并且while 条件始终为False

    如果您希望while 循环在for 循环的每次迭代中再次运行,请在for 循环中重置cCount

    corCols = 10
    corRows = 8
    for rCount in range(corRows):
        cCount = 0
        while cCount < corCols:
            print "***" + str(cCount)
            cCount += 1
        print "###" + str(rCount)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 2017-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多