2016-07-26 113 views
3

本練習來自Zed Shaw書中的第20章。Python中的行打印

我想了解行號的行爲。

當我使用下面的代碼時,文本文件中的行號被打印爲4,這是錯誤的。它在第三行。

current_line += current_line 

但是,行號顯示正確的,當我用下面的

current_line = current_line + 1 

能有人好心解釋什麼是在上面兩行的差別,看起來一樣,我和它爲什麼做一個區別。

以下是完整代碼:

from sys import argv 
script, input_file = argv 

def print_all(f): 
    print f.read() 

def rewind(f): 
    f.seek(0) 

def print_a_line(line_count, f): 
    print line_count, f.readline() 

current_file = open(input_file) 

print "First let's print the whole file:\n" 

print_all(current_file) 

print "Now let's rewind, kind of like a tape." 

rewind(current_file) 

print "Let's print three lines:" 

current_line = 1 
print_a_line(current_line, current_file) 

current_line += current_line 
print_a_line(current_line, current_file) 

#current_line = current_line + 1 
current_line += current_line 
print_a_line(current_line, current_file) 
+0

只要你知道,我已經提出並收藏這個問題,因爲它是一個良好的初學者問題的一個很好的例子。你已經描述了這個問題(包括預期的和實際的結果),清楚地說明了你的問題,並且包含了一個[MCVE](http://stackoverflow.com/help/mcve)。許多初學者(編程和使用堆棧溢出)忽略了其中的一個或多個。請不要停止以這種方式提問。 – skrrgwasme

+0

非常感謝你:) - 我會牢記這些要點,提出問題前進。 – Sarat

回答

2

current_line + = current_line擴展出

current_line = current_line + current_line 

所以,讓我們來看看你做了什麼,通過擴大它(我們將忽略打印語句)。

current_line = 1 
current_line = current_line + current_line # (1 + 1 = 2) 
#current_line = 2 
current_line = current_line + current_line # (2 + 2 = 4) 
#current_line = 4 

我想你想用

current_line += 1 
+0

謝謝Taztingo。我現在知道了。 – Sarat

+0

沒問題:)。 – Taztingo

0

你不爲1的常數因子增加的current_line的價值,而不是你一幾何級數增加

current_line += current_line分配的current_line值設定爲本身+本身:

current_line = 5 
current_line = current_line + current_line 
>>> current_line 
>>> 10 

current_line = current_line + 1current_line += 1+=1是用於增加由1的值語法糖)由1

增加 current_line
current_line = 5 
current_line = current_line + 1 
current_line += 1 
>>> current_line 
>>> 7 

由於current_line是一個計數器爲行號,+= 1應該在這種情況下使用。

+0

謝謝。我是編程的初學者,我不知道它是如何工作的。 – Sarat

+0

@Sarat Yeeep無後顧之憂! – ospahiu