Parameters and Unpacking Variable in Python

Parameters and Unpacking Variable in Python

In this exercise, we will cover one more input method you can use to pass variables to a script (script being another name for your. You know how you type python py to run the py file? Well the py part of the command is called an “argument.” What we’ll do now is write a script that also accepts arguments.

1 from sys import argv
3 script, first, second, third = argv
5 print "The script is called:", script
6 print "Your first variable is:", first
7 print "Your second variable is:", second
8 print "Your third variable is:", third


 Your first variable is: first
 Your second variable is: 2nd
 Your third variable is: 3rd

On line 1 we have what’s called an “import.” This is how you add features to your script from the Python feature set. Rather than give you all the features at once, Python asks you to say what you plan to use. This keeps your programs small, but it also acts as documentation for other programmers who read your code later.

The argv is the “argument variable,” a very standard name in programming that you will find used in many other languages. This variable holds the arguments you pass to your Python script when you run it. In the exercises you will get to play with this more and see what happens.

Study Drills

  1. Try giving fewer than three arguments to your script. See that error you get? See if you can explain it.
  2. Write a script that has fewer arguments and one that has more. Make sure you give the unpacked variables good names.
  3. Combine raw_input with argv to make a script that gets more input from a user.
  4. Remember that modules give you features. Modules. Modules. Remember this because we’ll need it later.

When I run it I get ValueError: need more than 1 value to unpack.

Remember that an important skill is paying attention to details. If you look at the What You Should See (WYSS) section, you see that I run the script with parameters on the command line. You should replicate how I ran it exactly.

What’s the difference between argv and raw_input()?

The difference has to do with where the user is required to give input. 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().

Are the command line arguments strings?

Yes, they come in as strings, even if you typed numbers on the command line. Use int() to convert them just like with raw_input().

How do you use the command line?

You should have learned to use it real quick by now, but if you need to learn it at this stage, then read the Command Line Crash Course appendix.