A piece of Python

The other day, a friend of mine from the university IM:ed me, asking for reading material on Python. My first instinct was to refer her to the Python documentation. Then my curiosity grabbed hold of me. It turns out she had an assignment, which boiled down to reading the first two lines in a sequence of text files.

She had crafted a solution which almost worked, but the inner loop (the one outputting lines 1 and 2 from each file) was giving her a head-ache, so she asked me for input.

My first approach was this:

c = 0
for line in file:
    if c >= 2:
    # do stuff with "line"
    c += 1

It was eerily similar to her attempt, but I felt uncomfortable with the code… it just didn’t “feel” right. It felt as if there had to be a less stupid way to go about this problem (not calling her solution stupid, this was her first attempt at coding Python, I on the other hand, should be ashamed).

Thinking about it, one really didn’t need a loop at all for this assignment. In order to read the first two lines in a file, you’d need a handle to the file, and then call the function readline() on that handle, twice.


This is, of course, not the least bit maintainable, for instance, what would the solution be if the assignment was changed to read the 5, 10 or 15 first lines of text? No, that would just be plain ugly. So we bring the loop back in from the cold, to manage the number of lines to extract:

for i in range(1, NUMBER_OF_LINES):

The assignment didn’t say anything about line numbering, and although we could use “i” for this purpose it seems wasteful to assign a value to it and then ending up never using it, but seeing as we would otherwise have to create a counter anyway, to manually manage when to break out of the loop, I believe this solution to be the cleanest, simplest, most readable, and thus, the most beautiful. At least until someone comes up with something even better.

Writing this post, I am currently pondering about a while-loop approach, something along the lines of:

lines_left = NUMBER_OF_LINES
while lines_left > 0:
    lines_left -= 1

However, now seeing it in writing, and not just in my mind I realize that it is double the size of the previous solution, and for what? Trying to get away from  a counter variable, which I end up using anyway, only backwards… no, the for-loop won this round.

Tags: ,

Comments are closed.