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]
sys. argv is a list in Python that contains all the command-line arguments passed to the script.
argv is a list in Python, which contains the command-line arguments passed to the script. With the len(sys. argv) function you can count the number of arguments.
sys. argv[1] contains the first command line argument passed to your script.
let's say on the command-line you have:
C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises \google-python-exercises\hello.py John
to make it easier to read, let's just shorten this to:
C:\> hello.py John
argv
represents 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 1
in other words, sys.argv[0] == 'hello.py'
and sys.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) >= 2
just checks whether you entered at least two elements. in this case, we entered exactly 2.
now let's translate your code into English:
define main() function: if there are at least 2 elements on the cmd-line: set 'name' to the second element located at index 1, e.g., John otherwise there is only 1 element... the program name, e.g., hello.py: set 'name' to "World" (since we did not get any useful user input) display 'Hello' followed by whatever i assigned to 'name'
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 use sys.argv[2]
, which was "Paul
" -- can you see in this case that len(sys.argv) == 3
because there are 3 elements in the sys.argv
list?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With