本练习来自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