仅打印最终结果,而不是所有中间结果

2024-04-26 07:23:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在写一个从文件中读取数据的程序。每四行是一年,我需要使用计数器来计算总的年数,但是当我运行程序时,输出窗口显示:

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)+ '.')

如何使它只显示一行而不更改任何其他信息?你知道吗


Tags: ofthe程序numberifiscountline
1条回答
网友
1楼 · 发布于 2024-04-26 07:23:10

你的问题

压痕错误。您的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循环完成后执行。你知道吗

相关问题 更多 >