【问题标题】:Nested While loop in PythonPython中的嵌套While循环
【发布时间】:2009-09-14 12:43:21
【问题描述】:

我是 python 编程的初学者。我编写了以下程序,但它没有按我的意愿执行。代码如下:

b=0
x=0
while b<=10:
    print 'here is the outer loop\n',b,
    while x<=15:
        k=p[x]
        print'here is the inner loop\n',x,
        x=x+1
    b=b+1

有人可以帮助我吗?我真的会感激不尽! 问候, 吉拉尼

【问题讨论】:

  • 你想让它做什么?解释更多
  • 输出是什么?你期望它是什么?
  • 你对代码有什么要求?
  • 什么是 p?什么是k?你想让它重新进入内循环吗?如果是这样,您需要在外部循环的顶部将 x 重置为 0。
  • 谢谢我得到答案............!

标签: python while-loop


【解决方案1】:

不确定您的问题是什么,也许您想将 x=0 放在内部循环之前?

你的整个代码看起来不像 Python 代码......像这样的循环最好像这样完成:

for b in range(0,11):
    print 'here is the outer loop',b
    for x in range(0, 16):
        #k=p[x]
        print 'here is the inner loop',x

【讨论】:

  • range(0,11) 是更好的写 range(11)。零是默认的下限。
  • 更好的是使用xrange(11)range 创建一个完整的列表并将其返回给调用者。 xrange 返回一个生成器函数,它会延迟元素的分配,直到它们被请求。对于 16 个元素的数组,这可能不是很大的区别。但是,如果您数到 10,000,那么xrange 肯定更好。
【解决方案2】:

因为您在外部 while 循环之外定义了 x,所以它的范围也在外部循环之外,并且在每个外部循环之后它都不会被重置。

要解决这个问题,请在外循环内移动 x 的定义:

b = 0
while b <= 10:
  x = 0
  print b
  while x <= 15:
    print x
    x += 1
  b += 1

一个更简单的方法是使用 for 循环:

for b in range(11):
  print b
  for x in range(16):
   print x

【讨论】:

    【解决方案3】:

    您需要在处理完内部循环后重置您的 x 变量。否则你的外循环将在不触发内循环的情况下运行。

    b=0
    x=0
    while b<=10:
        print 'here is the outer loop\n',b,
        while x<=15:
            k=p[x] #<--not sure what "p" is here
            print'here is the inner loop\n',x,
            x=x+1
    x=0    
    b=b+1
    

    【讨论】:

      【解决方案4】:

      运行您的代码时,出现错误:

      'p' is not defined 
      

      这意味着您正在尝试使用 list p 之前的任何内容。

      删除该行让代码运行并输出:

      here is the outer loop
      0 here is the inner loop
      0 here is the inner loop
      1 here is the inner loop
      2 here is the inner loop
      3 here is the inner loop
      4 here is the inner loop
      5 here is the inner loop
      6 here is the inner loop
      7 here is the inner loop
      8 here is the inner loop
      9 here is the inner loop
      10 here is the inner loop
      11 here is the inner loop
      12 here is the inner loop
      13 here is the inner loop
      14 here is the inner loop
      15 here is the outer loop
      1 here is the outer loop
      2 here is the outer loop
      3 here is the outer loop
      4 here is the outer loop
      5 here is the outer loop
      6 here is the outer loop
      7 here is the outer loop
      8 here is the outer loop
      9 here is the outer loop
      10
      >>>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 2011-02-19
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        • 1970-01-01
        • 1970-01-01
        • 2015-04-16
        相关资源
        最近更新 更多