In this exercise we will cover one more input method you can use it for passing parameters in variables to a script (script being another name for your .py files). You know how you type python ex13.py to run the ex13.py file? Well the ex13.py part of the command is called an “argument.” What we’ll do now is write a script that also accepts arguments.
Type this program and I’ll explain it in detail:
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)
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.
Line 2 “unpacks” argv so that, rather than holding all the arguments, it gets assigned to four variables you can work with: script, first, second, and third. This may look strange, but “unpack” is probably the best word to describe what it does. It just says, “Take whatever is in argv, unpack it, and assign it to all of these variables.”.
After that we just print them out like normal.
Hold Up! Features Have Another Name
I call them “features” here (these little things you import to make your Python program do more) but nobody else calls them features. I just used that name because I needed to trick you into learning what they are without jargon. Before you can continue, you need to learn their real name: modules.From now on we will be calling these “features” that we import modules. I’ll say things like, “You want to import the sysmodule.” They are also called “libraries” by other programmers, but let’s just stick with module
Run the code for Passing Parameters
Exercise of the day
- This is big exercise code, your code should be able to perform below tasks:
- Get Name of person using argv.
- Use that Name for asking question from user, ask 2 question of your choice. e.g “Hello Akar What is your age?”
- Once question is asked script should prompt “>” for user to insert values. Like below image
- Print all the values.