3

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

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

4

4 回答 4

26

不确定你的问题是什么,也许你想把它放在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
于 2009-09-14T12:48:49.033 回答
14

Because you defined the x outside of the outer while loop its scope is also outside of the outer loop and it does not get reset after each outer loop.

To fix this move the defixition of x inside the outer loop:

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

a simpler way with simple bounds such as this is to use for loops:

for b in range(11):
  print b
  for x in range(16):
   print x
于 2009-09-14T12:57:00.840 回答
0

When running your code, I'm getting the error:

'p' is not defined 

which means that you are trying to use list p before anything is in it.

Removing that that line lets the code run with output of:

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
>>>
于 2009-09-14T12:55:44.940 回答
0

您需要在处理内部循环后重置您的 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
于 2016-08-09T17:56:48.550 回答