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[1]

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 print function, and 2) concatenation with the variable we created with the command line input.

Now we can pass arguments to our script:

$ python3 Trey
Hello Trey!
$ python3 earthlings
Hello earthlings!


Your Turn: Arguments 🏁

Argument Exercises

Add More

Edit the program so it will take 3 numbers and return the sum.

Example usage:

$ python3.6 3 5.2 2
$ python3.6 -7 2 1
$ python3.6 -2 -1 5.3

Difference Between

Make a program that takes two numbers and prints the positive difference between these two numbers:

Example usage:

$ python3.6 3 5
$ python3.6 6 3.5
$ python3.6 -7 2