-4

I am reading Learn Python the Hard Way (3rd Ed.) and there is an exercise I was trying, but I am just unable to get it; the arguments and parameters stuff (Exercise 13).

I've read other answers on the site for the same question, but my doubts remain. Could someone explain this code to me?

from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your third variable is:", third
print "Your second variable is:", second
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
sunp
  • 21
  • 6
  • What exactly don't you understand? Do you get some of the lines? None of them? Which *"other answers on the site"* have you read; what did they make clearer; and what is still unclear? Have you read all of the explanation? Have you done the study drills? What happened? And why do you think an answer here will be better than LPtHW itself? Please see http://meta.stackoverflow.com/q/253894/3001761 – jonrsharpe Oct 13 '14 at 15:48
  • I know my question was to broad but "script, first, second, third = argv" this part specifically and some conceptual clarity on argv, and how to use it should help... – sunp Oct 13 '14 at 16:01
  • 1
    That specific part is specifically explained in Ex. 13 (third paragraph after the code, starting *'Line 3 "unpacks" `argv`'*). Also, running the code should make it clear what's happening. When to use `argv` vs. `raw_input` is also explained (see the second "Common Student Question"). – jonrsharpe Oct 13 '14 at 16:02
  • Ok, got it. "If they give your script inputs on the command line, then you use argv. If you want them to input using the keyboard while the script is running, then use raw_input()." Okay but still it would be nice to have "good simple easy to digest and practical" argv example?...for a non programmer... – sunp Oct 13 '14 at 16:08
  • That is exactly what that exercise is designed to give you... – jonrsharpe Oct 13 '14 at 16:09
  • yup...i guess, thanks. – sunp Oct 13 '14 at 16:11

1 Answers1

0

As @jonsharpe said in his comment, the program you provided runs as follows:

  1. Load a reference to module sys, get the element argv and store it in the global variables.
  2. Take the argv global variable and unpack its values, then save each of its values in order: save the 1st in script, the 2nd in first, the 3rd in second, and 4th in third. This step may throw errors when not enough values can be unpacked to store in the variables.
  3. Print the string The script is called: followed by the value that script holds. If script contains a non-string value, the value of str(script) is written.
  4. Print the string Your first variable is: followed by the value that first holds.
  5. Print the string Your second variable is: followed by the value that second holds.
  6. Print the string Your third variable is: followed by the value that third holds.
SonicARG
  • 499
  • 9
  • 14