2013-05-05 102 views
0

下面是代碼:有人可以向我解釋這段代碼嗎?

count = 0 
phrase = "hello, world" 
for iteration in range(5): 
    while True: 
     count += len(phrase) 
     break 
    print("Iteration " + str(iteration) + "; count is: " + str(count)) 

我很困惑,在count += len(phrase)

我覺得算+= len(phrase) =>count = count + len(phrase)

當計+= 1那麼它是可以理解的,它增加1每下一個迭代但是這裏遍歷整個長度,所以我無法得到它背後的邏輯。我請求任何人都可以逐行解釋我在這段代碼中實際發生的事情。謝謝!

+6

的'而TRUE'和'break'只是混淆。結果是相同的,如果他們被刪除。 – unutbu 2013-05-05 13:06:43

+0

@unutbu謝謝! – user1938918 2013-05-05 13:22:44

回答

3
count = 0 
phrase = "hello, world" 
for iteration in range(5): #iterate 5 times 
    while True: 
     #count = count + len(phrase) 
     count += len(phrase) # add the length of phrase to current value of count. 
     break     # break out of while loop, while loop 
           # runs only once for each iteration 
    #print the value of current count 
    print("Iteration " + str(iteration) + "; count is: " + str(count)) 

因此,簡而言之程序加入phrase長度count 5倍。

輸出:

Iteration 0; count is: 12 # 0+12 
Iteration 1; count is: 24 # 12+12 
Iteration 2; count is: 36 # 24+12 
Iteration 3; count is: 48 # 36+12 
Iteration 4; count is: 60 # 48+12 

上述程序是大致等效於:

count = 0 
phrase = "hello, world" 
for iteration in range(5): 
    count = count + len(phrase) 
    print("Iteration " + str(iteration) + "; count is: " + str(count)) 
+2

這相當於'count = 5 * len(「hello,world」)'...... – 2013-05-05 13:15:16

+0

@Ashwini Chaudhary感謝您的詳細解釋! – user1938918 2013-05-05 13:25:13

+0

@Thijs Van謝謝! – user1938918 2013-05-05 13:25:43

3

你對+=的直覺是正確的; +=運營商意味着原地添加和不可變價值類型,如int正好count = count + len(phrase)相同的東西。

外部for循環運行5次;所以count最終設置爲phrase長度的5倍。

您可以完全刪除while True:循環。它開始一個循環,迭代一次;在第一次迭代期間,break結束循環

此代碼中沒有任何內容是遍歷整個phrase值的任何東西。只有它的長度(12)被查詢,並加入到count,因此最終值是5次12等於60

+0

謝謝你的解釋! – user1938918 2013-05-05 13:26:19

相關問題