Python中的嵌套While循环

Python中的嵌套While循环,python,while-loop,Python,While Loop,我是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 b=0 x=0 当b不确定你的问题是什么时,也许你想把x=0放在内环之前 你的

我是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
b=0
x=0

当b不确定你的问题是什么时,也许你想把
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

运行代码时,如果“'p'未定义”,则会出现错误,这意味着您试图在数组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
>>> 

因为您在外部while循环之外定义了x,所以它的作用域也在外部循环之外,并且在每个外部循环之后它不会重置

要解决此问题,请在外环内移动x的退约:

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

处理内部循环后,需要重置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
b=0
x=0

B你想让它做什么?进一步解释输出是什么?你期望它是什么?你想要代码做什么?p是什么?什么是k?你想让它重新进入内部循环吗?如果是这样,你需要在外循环的顶部将x重置为0。谢谢,我得到了答案。。。。。。。。。。!范围(0,11)是更好的写入范围(11)。零是默认的下限。更好的是使用
xrange(11)
range
创建一个完整的列表并将其返回给调用者
xrange
返回一个生成器函数,该函数将延迟元素的分配,直到请求它们为止。对于一个16元素的数组,它可能不会有太大的区别。然而,如果你数到10000,那么
xrange
肯定更好。
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