我在写一个从文件中读取数据的程序。每四行是一年,我需要使用计数器来计算总的年数,但是当我运行程序时,输出窗口显示:
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)+ '.')
如何使它只显示一行而不更改任何其他信息?你知道吗
你的问题
压痕错误。您的
print()
在while
循环中:因此,在每个循环之后,执行这个
print()
。你知道吗解决方案
只需删除
print()
之前的缩进级别:由于您的
print()
现在位于while
循环之外,它将仅在while
循环完成后执行。你知道吗相关问题 更多 >
编程相关推荐