2009-09-14 127 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