Lesson 20

At first glance, this exercise appeared simple for me, until I got into it a bit. First,

def print_all(f):

That f throws me! I tried to see in the code what it was doing, but I couldn’t, and besides, the point of each lesson is to teach NEW ideas, not expect the student (that’s me!) to understand the language of code intuitively – otherwise, hey, who needs lessons?

So I didn’t understand that right at first, but that’s okay, because further on, we’re given:

print "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

Hey! Awesome! Given my experience with looping, whether WHILE or IF and maybe some other type I am forgetting right now, I can see a mile away that this can be WAY cleaned up per my specifications! This hugely makes up for the not-knowing of the utility of f previously!

So I go ahead and run the program, something that will print out a text file line by line as well as “rewinding” it, and then I set immediately to cleaning it up:

i = 0
current_line = 1
while i < 3:
print_a_line(current_line, current_file)
current_line += 1
i += 1

Woo-hoo! Nine lines condensed down to six, and while that may not sound like much, a) it can probably be condensed more, and b) it’s a much simpler process, at least for me, to follow. I am thinking I may not even need the i indexing!

Let’s play around, then, a bit. I’m going to take out the i index and make the while loop dependent on current_line rather than on the index.

TOTALLY WORKS, OH YEAH, CHECK IT:


current_line = 1
while current_line <= 3:
print_a_line(current_line, current_file)
current_line += 1

FOUR LINES! So slim!

One last thing: re the f code question from before, well, it was addressed by Mr Shaw in the Common Student Questions portion! The f acts like a VHS-style “read head,” as in, the reading of the file stops at the line you read, and then our defined function rewind moves it back to the position we specify, in this case, the 0th byte, a.k.a. the beginning of the file!

EXERCISE CONQUERED!

EDIT of 13 October 2013: It occurs to me that altering variables is not the best practice for looping. Rather than adding values to current_line, it is a better idea to create an index like i and set current_line equal to the index, and then let the index do all the heavy lifting! Then, if I want to call the variable again, it will be unchanged! Woo-hoo!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s