在Python中嵌套While循环

Gil*_*ani 2 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
Run Code Online (Sandbox Code Playgroud)

有人能帮帮我吗?我将非常感激!此致,吉拉尼

Joc*_*zel 24

不确定你的问题是什么,也许你想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
Run Code Online (Sandbox Code Playgroud)

  • 范围(0,11)是更好的写入范围(11).零是默认下限. (3认同)

Jon*_*San 11

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

要修复此移动,外部循环中x的定义:

b = 0
while b <= 10:
  x = 0
  print b
  while x <= 15:
    print x
    x += 1
  b += 1
Run Code Online (Sandbox Code Playgroud)

一个简单的方法,简单的边界,如这是用于循环:

for b in range(11):
  print b
  for x in range(16):
   print x
Run Code Online (Sandbox Code Playgroud)