Sum of two numbers coming from the command line
I know this is a very simple program, but I am getting an out of range list error. Here is a program to take two numbers as command line arguments (when calling the script) and display the sum (using python):
import sys
a= sys.argv[1]
b= sys.argv[2]
sum=str( a+b)
print " sum is", sum
source to share
The error list index out of range
means that you are trying to access a list item outside of the list.
Example:
>>> mylist = ['hello', 'world']
>>> print mylist[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
In your case, the error comes from sys.argv[1]
or sys.argv[2]
.
Make sure you are actually passing something to the program from the command line.
source to share
Assuming your inputs are integers:
import sys
summ = sum(map(int,sys.argv[1:])
print "sum is ", summ
or
import sys
summ = sum(int(i) for i in sys.argv[1:])
print "sum is ", summ
If not, change int to float.
The second method is probably more pythonic, but the first is slightly faster in this case.
>>>import timeit
>>>t1 = timeit.Timer("sum(map(int,['3','5','7','9']))")
>>>t2 = timeit.Timer("sum(int(i) for i in ['3','5','7','9'])")
>>>print t1.timeit()
3.0187220573425293
>>>print t2.timeit()
3.4699549674987793
source to share
If your error is "index index out of range", the problem is that your list is missing items. What list? The only list you are using is , so you need to pass more items on the command line to fill it. sys.argv
Alternatively, check the length of the argument list with len(sys.argv)
and suggest interactively (using for example raw_input()
) to get the values if they are not in sys.argv
.
source to share
If you want to sum numbers as floating point numbers, use "float" instead of "int" as in the following snippet.
import sys
try:
a, b = sys.argv[1:3]
print "sum is ", float(a) + float(b)
except ValueError:
print "please give me two numbers to sum"
Beware that floating points are different from real numbers, so you can get seemingly "strange" results, which are documented on the Internet.
source to share