John.J
John.J

Reputation: 37

Getting Row Count With for-loop

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

Upvotes: 1

Views: 1839

Answers (2)

J Arun Mani
J Arun Mani

Reputation: 620

Just move the print to end of the loop.

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

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71610

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.

Upvotes: 1

Related Questions