Skip to content Skip to sidebar Skip to footer

Exercise 41: Learning To Speak Object Oriented

I am at exercise 41 and to be honest I am extremely confused. I don't know if it's because i've been looking at the damn thing for hours, if my brain is fried, or what? I've gone o

Solution 1:

No, the code sets PHRASE_FIRST to False.

Then the sys.argv list is tested; if there are 2 values in that list, and the second value is equal to the string "english", then PHRASE_FIRST is rebound to True.

sys.argv is the list of command-line arguments; sys.argv[0] is the name of the script, and any extra elements in that list are strings passed in on the command line:

python script.py foo bar

becomes

['script.py', 'foo', 'bar']

in sys.argv. In this case, if you run the script with:

python script.py english

then PHRASE_FIRST is set to True, otherwise it remains False.


Solution 2:

What it's doing is setting a variable PHRASE_FIRST to either False, or under a certain circumstance, True. The first part is straightforward:

PHRASE_FIRST = False 

The second part resets PHRASE_FIRST to be True if:

len(sys.argv) == 2 and sys.argv[1] == "english"

sys.argv is the command line arguments, starting with the name of the program, i.e. exercise_41.py english becomes ['exercise_41.py', 'english'], and said second argument (sys.argv[1]) has to be "english"

By not having the len check, the second part would error out of range. That's the only reason for the len. If those are both true,

    PHRASE_FIRST = True

All three lines could technically be rewritten more directly as:

PHRASE_FIRST = len(sys.argv) == 2 and sys.argv[1] == "english"

But that's a bit harder to read for beginners


Post a Comment for "Exercise 41: Learning To Speak Object Oriented"