Question

I've been working through Learn Python the Hard Way, and I'm having trouble understanding what's happening in this part of the code from Example 41 (full code at http://learnpythonthehardway.org/book/ex41.html).

PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST = True

I assume this part has to do with switching modes in the game, from English to code, but I'm missing how it actually does that. I know that the len() function measures length, but I'm confused as to what sys.argv is in this situation, and why it would have to equal 2, and what the 1 is doing with sys.argv[1].

Thank you so much for any help.

Était-ce utile?

La solution

The len function does measure length. In this case it is measuring the length of an list (or often called an array).

The sys.argv represents a list of strings passed in via command line arguments. Here is some documentation on it http://docs.python.org/2/library/sys.html

An example from the command line:

python learning.py one two

This will have a total of three arguments passed into sys.argv. The arguments are learning.py, one and two as strings

The code,

sys.argv[1]

is retrieving whatever is stored at index one for the sys.argv list. For the example above, this would return the string 'one'. It is important to remember that python lists are zero indexed. The first element of a non empty list will always be index 0.

Autres conseils

sys.argv accepts command line arguments that can be accessed like a list

sys.argv[0] is always the name of the script and the rest follow

The first half of your if() statement len(sys.argv) == 2 is used to make sure you don't get an IndexoutOfBoundsException, if this returns false, the program will exit and not call the next statement which would have had an error.

The next statement checks the program's command line argument sys.argv[1] == "english" just makes sure that the correct command line argument was entered. If you run the program like this

python myScript.py english

Then that statement will return True

sys.argv seems to be an array, and the if statement is saying that if the length of the array is 2 and the second element in the array (index 1) is the string "english", then to make the variable PHRASE_FIRST equal to True.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top