I'm writing a program that reads data from a file. Every fourth line is a year and I need to use a counter to count the total number of years but when I run the program, the output window shows this:
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.
I only need to print the last line, not all of them. This is how I have written it:
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)+ '.')
How do I get it to display only one line without changing any of the other information?
The indentation is wrong. Your print()
is inside the while
loop:
while line != '':
[...]
print('The total number of years is ' + str(total_year) + '.')
Thus, after each loop, this print()
is executed.
Simply remove an indentation level before your print()
:
while line != '':
[...]
print('The total number of years is ' + str(total_year) + '.')
With your print()
now located outside the while
loop, it will only be executed after the while
loop is done.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.