Command Line Arguments¶
Let’s change our command-line script so that it can accept arguments too, meaning we can tell it who to say hello to when we run the program.
We’re going to use some Python magic from the standard library to make this happen. Right now we don’t need to worry so much about what Python is doing, so much as how to make it do it. Here’s what our program will look like:
import sys name = sys.argv print("Hello " + name)
We’re going to use the
sys Python module, which we import on the first line. Then we’re going to assign the command line imput to the variable
name. The synax here is a little strange-looking at first. As you move through your Python journey you’ll learn more about methods and slices, but we’re going to hop right over that for now. Just type the code exactly as you see it above.
The last thing we’re doing there are two things you’ve already seen: 1) the
Now we can pass arguments to our script:
$ python3 greetings.py Trey Hello Trey! $ python3 greetings.py earthlings Hello earthlings!
Your Turn: Arguments 🏁¶
Edit the program
add.py so it will take 3 numbers and return the sum.
$ python3.6 add.py 3 5.2 2 10.2 $ python3.6 add.py -7 2 1 -4.0 $ python3.6 add.py -2 -1 5.3 2.3
Make a program
difference.py that takes two numbers and prints the positive difference between these two numbers:
$ python3.6 difference.py 3 5 2.0 $ python3.6 difference.py 6 3.5 2.5 $ python3.6 difference.py -7 2 9.0