簡體   English   中英

僅打印最終結果,而不是所有中間結果

[英]Printing only final result instead of all intermediate results

我正在編寫一個從文件讀取數據的程序。 每四行是一年,我需要使用一個計數器來計算總年數,但是當我運行程序時,輸出窗口顯示如下:

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循環中:

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循環完成后執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM