Ex23 Help? - don't understand

Hi, I’ve been slowly making my way through ex23 of the book and I’m now in the part of dissecting the code.

I’m having a bit of trouble understanding the first function (probs will have in 2nd function too, but that’s for later), anyway I don’t understand how we are preventing the loop. And I’m having some trouble with the if part too.

 5 def main(language_file, encoding, errors):
 6     line = language_file.readline()
 7
 8     if line:
 9         print_line(line, encoding, errors)
10         return main(language_file, encoding, errors)

I understand that we’re defining a function, it’s parameters and that we’re going to do something with those parameters, but what?

We’re defining line as the program reading a line on our language file - which gives us an empty string? what is that? like a " " ?

Then we’re saying if line, but if what?
The book says if line returns something, but is an empty string considered a something? And how does the program check if this is true with only if? There’s no ==

I also don’t understand what the conditions for if line are
If it’s true (the line has something in it?) then indented lines below it are used? and thus making a loop?
And if it’s false then they aren’t? then how do we use the print_line function?
Does the program stop there then? and if so, how is it even possible to not get something from line then? .readline() only returns an empty string right? What needs to happen for it to not?

I guess I’m just not understanding the different paths this code can take, what are the conditions for them and what happens at the end of each one of them. Much confusion basically.

Also thank you for reading this long post

A few of your assumptions aren’t quite correct, so let’s break it down.

def main(language_file, encoding, errors):
     line = language_file.readline()
 
     if line:
        print_line(line, encoding, errors)
        return main(language_file, encoding, errors)

So we are defining a function called main. As you say, it takes 3 arguments; the language file we are going to read, the encoding type, and errors.

‘line’ is a variable we are assigning whatever comes from reading a line (of text) from whatever we add as the language file. We don’t want to hard code what that file is in our code so the argument ‘language_file’ is a reference.

The ‘if’ statement is a shortcut for ‘if True’. So we are saying, if it’s true that line has some text in it (from the readline step) then do the following… (which in this case is print the line using the ‘print_line’ defines function.

The super confusing bit is that it the returns itself, ie the main function. This is an example of recursion.

At some point the language_file won’t have anymore lines to read, and therefore the line variable will evaluate to False in the if statement, and it will stop.

Thank you so much!
This really cleared it up for me ^^

1 Like
A free service run by Zed A. Shaw for learncodethehardway.org.