In the below code I understand that sys.argv uses lists, however I am not clear on how the index’s are used here.
def main():
if len(sys.argv) >= 2:
name = sys.argv[1]
else:
name = 'World'
print 'Hello', name
if __name__ == '__main__':
main()
If I change
name = sys.argv[1]
to
name = sys.argv[0]
and type something for an argument it returns:
Hello C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py
Which kind of make sense.
Can someone explain how the 2 is used here:
if len(sys.argv) >= 2:
And how the 1 is used here:
name = sys.argv[1]
Let’s say on the command-line you have:
To make it easier to read, shorten it to:
argvrepresents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py" is element 0, "John" is element 1In other words,
sys.argv[0] == 'hello.py'andsys.argv[1] == 'John'… but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.len(sys.argv) >= 2just checks whether you entered at least two elements. in this case, we entered exactly 2.Now let’s translate your code into English:
So what does this mean? It means that if you enter:
hello.py", the code outputs "Hello World" because you didn’t give a namehello.py John", the code outputs "Hello John" because you didhello.py John Paul", the code still outputs "Hello John" because it does not save nor usesys.argv[2], which was "Paul" — can you see in this case thatlen(sys.argv) == 3because there are 3 elements in thesys.argvlist?