我正在编写一个从文件中读取数据的程序。每四行都是一年,我需要使用计数器来计算总年数,但是当我运行程序时,输出窗口会显示:
The total number of years is 1.
The total number of years is 2.
The total number of years is 3.
The total number of years is 4.
The total number of years is 5.
The total number of years is 6.
The total number of years is 7.
The total number of years is 8.
The total number of years is 9.
The total number of years is 10.
The total number of years is 11.
The total number of years is 12.
The total number of years is 13.
The total number of years is 14.
The total number of years is 15.
我只需打印最后一行,而不是全部。这就是我写的:
count = 0
line_count = 0
total_year = 0
while line != '':
count += 1
if len(line) > 1:
if line_count % 4 == 0:
total_year += 1
year=int(line)
line = infile.readline()
line_count+=1
print('The total number of years is ' + str(total_year)+ '.')
如何在不更改任何其他信息的情况下仅显示一行?
答案 0 :(得分:2)
缩进是错误的。您的print()
位于while
循环内:
while line != '':
[...]
print('The total number of years is ' + str(total_year) + '.')
因此,在每个循环之后,执行此print()
。
只需在print()
:
while line != '':
[...]
print('The total number of years is ' + str(total_year) + '.')
当您的print()
现在位于while
循环之外时,它将仅在while
循环完成后执行。