Search code examples
pythonfor-loopincrementpost-incrementpre-increment

Why count doesn't behave normal in python for loop


I have a text file I'm reading from and just threw a counter on there to make sure I grabbed everything but when I implemented a simple counter it acted weird. It works now but I had to do the following:

f = open("street.txt", "r")
l = ""
count = -1
for line in f:
    if(line[0].isdigit()):
        l = line.replace('\n', '')

    else:
        count=count+1
        l = l + " " + line.replace('\n', '')
        c = str(count) + ')'
        print(c + l + '\n')

Essentially I was attempting to just run through this file, add every other line to the previous line then number them just as a check with a count variable, that I covered everything. For some reason when the count was running it started at 2 when I had count initially set to 0. It wouldn't print out "1)" until I changed count to -1 initially. That print statement is an L, not a 1. I have no idea why it was doing that. I didn't get an error, it ran fine just with the wrong numbers for about 4-5 runs. And that's an L in the print statement...which should be fairly obvious from the if statement but just in case.


Solution

  • Just initialize count with 0 and increment statement should be in the last.

    l = l + " " + line.replace('\n', '') 
    c = str(count) + ')' 
    print(c + l + '\n')
    count+=1