本練習來自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)
只要你知道,我已經提出並收藏這個問題,因爲它是一個良好的初學者問題的一個很好的例子。你已經描述了這個問題(包括預期的和實際的結果),清楚地說明了你的問題,並且包含了一個[MCVE](http://stackoverflow.com/help/mcve)。許多初學者(編程和使用堆棧溢出)忽略了其中的一個或多個。請不要停止以這種方式提問。 – skrrgwasme
非常感謝你:) - 我會牢記這些要點,提出問題前進。 – Sarat