CS 125
Homework 3

Assignment hw3
Files arguments.py count.py
Due 4:00 pm Mon Oct 11

When you run a python program from the bash shell, you can supply it with command line arguments (in the same way that you give command line arguments to linux commands). In order to get access to the commands inside your python program, you do the following:

  1. Import the sys module

  2. The arguments are available as a list of strings called sys.argv.

  3. The program name is actually the first item in the list, so sys.argv[0] is the program name.

  4. So if you write a program called prog.py, and you run it like this:

python prog.py a b 12 foo

then in the program

sys.argv will be the list ["prog.py", "a", "b", "12", "foo"].

To give command line arguments when you run a program in IDLE, choose “Run… Customized” from the Run menu and IDLE will ask for the command line arguments.

Part 1

Write a program called arguments.py that prints its command line arguments one per line, not including the program name.

Sample runs:

> python arguments.py 1 2 3 4
1
2
3
4
>
> python arguments.py foo
foo
>
> python arguments.py foo bar xyzzy plugh
foo
bar
xyzzy
plugh
>

In the next run, no arguments are given, so the program prints nothing.

> python arguments.py
>

In the next run, the words are enclosed in quotes. Bash makes quoted strings into a single argument.

> python arguments.py "this is one argument"
this is one argument
>

Part 2

Write a program called count.py that takes a single command line argument (call it n), converts that argument to an int, and prints the numbers from 1 to n on a single line.

To do the conversion, use something like n = int(sys.argv[1]).

Sample runs:

> python count.py 4
1 2 3 4 
>
> python count.py 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
>
> python count.py 0
>