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
You must do this:
import sys
a, b = sys.argv[1:2]
summ = int(a) + int(b)
print "sum is", summ
No need for str () when printing an integer. But you should use int () if you want to add a and b as integers.
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.
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
su = int(a) + int(b)
print("sum is %d" % su)
And you have to be careful with your variable naming. sum
shadows inline, it is not a good practice to do this (that is, do not call variables inline functions or any globally defined name).
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
.
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.
Thanks everyone. I got an answer
for i in range (1.51): if i% 5 == 0: print i, "\ n" else: print i,