2012-11-09 54 views
0

我剛剛開始學習while循環。使用while循環迭代相同的數字

我想使用while循環迭代10次相同的數字。

我想通了,我怎麼能利用while循環,以阻止在某一點,因爲它增加

但我無法弄清楚如何停止在某一點,而無需添加1和設置限制。

這裏是我的代碼

i = 1 
total = 0 
while i < 11: 
    print i 
    i += 1 
    total = i + total 
print total 

這將打印

1,2,3,4,5,6,7,8,9,10,65

在單獨的行中

我該如何修改此結果?

1,1,1,1,1,1,1,1,1,1,10?

回答

5

只是打印文字1並添加1總:

while i < 11: 
    print 1 
    i += 1 
    total += 1 

你需要跟蹤你的循環多少次運行,並使用i因爲這是很好,但也不意味着你需要在每次運行時增加它。

如果在每個循環期間,您只想要加上一個,那就做那個,不要使用循環計數器。

+0

這仍然會在最後打印65而不是10。 。 。 – ernie

+0

@ernie:已更正。 –

+0

啊,我明白了。這完成了這項工作。我明白。謝謝 – Flow

0
i = 1 
total = 0 
res = [] 
while i < 11: 
    res.append(1) 
    i += 1 
print ', '.join(res) +', '+ str(sum(res)) 

或爲:

vals = [1 for _ in range(10)] 
print ', '.join(vals) +', '+ str(sum(vals)) 
0

while循環的意義就在於不斷循環,同時在一定條件爲真。看來你想執行一個動作n次,然後顯示執行動作的次數。正如Martijn所說,你可以通過打印文字來實現這一點。從更一般的意義上講,您可能想要考慮讓您的計數器與變量分開,例如:

count = 1 
number = 3 
while count <11: 
    print number*count 
print "While loop ran {0} times".format(count)