Zed Shaw’s “Learn Python the Hard Way” frequently asks you to “write out in English” what each and every line of a script does. I am struggling to do that with some stuff associated with the function (command?) argv because I don’t know what to name certain parts of the code. Heck, I don’t even know what to call argv–a function? A command? Variable? I know it’s a module. But back on track:
Here is the code from exercise 13:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
Zed states “The ‘argv’ is the “argument variable.” My question is, what is the name of the things to the left of the equals sign on line three?
Colloquially speaking, my urge is to call the words “script,” “first” etc. variables themselves–but that doesn’t seem right, since according to Zed argv is “the argument variable.”
I did not think calling them “arguments” is correct either; I’ve only read “argument” in terms of command line arguments.
“Parameters” seemed likely, since it was mentioned in the title of the exercise, but doing web searches with combinations of “equals sign,” “=,” “python,” “argv,” “definition” and so on wasn’t very enlightening. Searching for things is very difficult when you don’t know what they’re called.
I am very clear on what’s happening in this script, I’m just not clear on the name of a part of it. I am very sure I’m going to slap my forehead when this is answered.
The things to the left of the
"="are variables that get their value from the variable on the right.Given:
argvis a list of strings which in this case contains 4 items. These strings are “unpacked” and assigned to the four variables on the left of the=.argvgets its value is when a Python program is invoked from the command line, like this:in this case
argvwill contain['test.py', 'this', 'is', 'sure', 'cool']. These strings after the command are called “command line arguments” (see this tutorial) and the name of the script, and any arguments are stored inargv. This is a way to send information to the script when you start it.In this case the variables get the following values:
and
So:
is really equivalent to:
It’s only that Python lets you do this assignment in one nice swoop.
Note that you can pull out your command line arguments in any order using the appropriate index value.
This mechanism is used to communicate information the to the Python script. You can imagine running a program that expects an input file and and output file. Instead of hardcoding them in your script, you could provide them on the command line. E.g.,