2009-09-14 145 views
1

我是一名Python编程初学者。我写了下面的程序,但没有按照我的要求执行。这里是代码:在Python中嵌套while循环

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 

有人可以帮助我?我会很感激! Regards, Gillani

+4

你想要它做什么?解释更多 – 2009-09-14 12:46:27

+0

输出是什么?你期望它是什么? – erelender 2009-09-14 12:49:35

+0

你想要什么代码? – ariefbayu 2009-09-14 12:49:48

回答

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 
+3

范围(0,11)写入范围更好(11)。零是默认的下限。 – Triptych 2009-09-14 16:29:58

+1

更好的是使用'xrange(11)'。 'range'创建一个完整列表并将其返回给调用者。 'xrange'返回一个生成器函数,它会延迟元素的分配,直到请求为止。对于16个元素的阵列,它可能不是一个巨大的差异。但是,如果你数到10000,那么'xrange'肯定更好。 – Nathan 2011-10-26 14:41:51

0

运行你的代码,如果“‘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 
>>> 
+0

谢谢我让它工作...........谢谢所有..........! – Gillani 2009-09-15 09:27:36

10

输出的代码运行,因为你所定义的外外的X while循环它的范围也外环以外,并没有得到每个之后重置外环。

要解决这个移动x的defixition外环内:用简单的界限,如本

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