Python中的嵌套While循环

pwuypxnk  于 2023-03-21  发布在  Python
关注(0)|答案(5)|浏览(148)

我是一个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

有人能帮我吗??我真的很感激!问候,吉拉尼

lymgl2op

lymgl2op1#

不知道你的问题是什么,也许你想把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
3bygqnnd

3bygqnnd2#

因为x是在while外部循环之外定义的,所以它的作用域也在外部循环之外,并且它不会在每个外部循环之后重置。
要修复此问题,请将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
wtzytmuj

wtzytmuj3#

你需要在处理完内部循环后重置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
q3qa4bjr

q3qa4bjr4#

当运行你的代码时,我得到错误:

'p' is not defined

这意味着您正在尝试在其中包含任何内容之前使用listp
删除这一行后,代码运行时的输出为:

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
>>>
watbbzwu

watbbzwu5#

如果你想测试一个嵌套的while循环中每个循环的迭代次数,并将其与for循环的迭代次数进行比较,我有一个程序可以做到这一点!

#Nested while loop
i=5
j=5
count=0
count1=0
while i>0:
    count+=1
    print("\t\t",count,"OUTER LOOP")
    while j>0:
        count1+=1
        print(count1,"INNER LOOP")
        j-=1
    i-=1

#Nested for loop
count=0
count1=0
for i in range(5):
    count+=1
    print("\t\t",count,"OUTER LOOP")
    for j in range(5):
        count1+=1
        print(count1,"INNER LOOP")

我附上输出供您参考。
OUTPUT OF NESTED WHILE LOOP [循环嵌套的输出][2]
1https://i.stack.imgur.com/ixM2k.png [2]:https://i.stack.imgur.com/1vsZp.png
编辑:Python中的嵌套while循环的工作原理与Python中的嵌套for循环完全相同。我用以下方式编辑了我的程序:

#Nested while loop
i=5
j=5
count=0
count1=0
while i>0:
    count+=1
    print("\t\t",count,"OUTER LOOP")
    while j>0:
        count1+=1
        print(count1,"INNER LOOP")
        j-=1
        break #Adding jump statement stops the iteration of inner loop and the outer loop gets executed again.
    i-=1

OUTPUT OF EDITED WHILE LOOP PROGRAM

相关问题