Your program is expecting two command line arguments.
sys.argv
is a list of command line arguments. The error IndexError: list index out of range
is telling you that you tried to get list item number 2, (with index 1), but the list doesn't have that many values.
You can reproduce that error in the shell:
>> alist = ['Item 0']
>> print(alist[1])
Since alist only has item with index 0 requesting items with higher indexes will cause that error.
Now, to your exact problem. The program is telling you it expected command line arguments, but they were not provided. Provide them!
Run this command:
python add.py 1 2
This will execute the script and pass 1
as the first argument, 2
as the second argument.
In your case the general format is
python add.py [n] [m]
Now at that point you might be (you should be) wondering what sys.argv[0]
is then, any why your n
number doesn't get assigned to sys.argv[1]
.
sys.argv[0]
is the name of the script running.
Further reading on command line arguments:
http://www.pythonforbeginners.com/system/python-sys-argv
Additional.
You could modify your script to be more descriptive:
import sys
if len(sys.argv) < 3: #script name + 2 other arguments required
print("Provide at least two numbers")
else:
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)