Ad

Getting Row Count With For-loop

- 1 answer

I need a function that finds all the lines that end with "end". Then, I need to count how many lines all together and use print to print out the number.

This is my code below:

count = 0

for line in open("jane_eyre.txt"):
    line_strip = line.rstrip()
    if line_strip.endswith(" end"):    
        lines = line_strip
        count += 1
        print("There are", count, "lines that end in 'end'.")  

Expected Result:

There are 4 lines that end in 'end'.

My Current Result:

There are 1 lines that end in 'end'.
There are 2 lines that end in 'end'.
There are 3 lines that end in 'end'.
There are 4 lines that end in 'end'.
Ad

Answer

It's a miss-indentation:

count = 0

for line in open("jane_eyre.txt"):
    line_strip = line.rstrip()
    if line_strip.endswith(" end"):    
        lines = line_strip
        count += 1
print("There are", count, "lines that end in 'end'.") # < look at now and before and compare.
Ad
source: stackoverflow.com
Ad