tags:

views:

459

answers:

7

Hi, I know it's a very basic program but I am getting an error of list out of range. Here is the program to take two numbers as command-line arguments (while invoking the script) and display sum (using python):

import sys
a= sys.argv[1]
b= sys.argv[2]
sum=str( a+b)
print " sum is", sum
A: 
su = int(a) + int(b)
print("sum is %d" % su)

And you should be careful with your variable naming. sum shadows the built-in, it's not a good practice to do that (that is, don't name variables as built-in functions or any globally defined name).

SilentGhost
+5  A: 

You should do this:

import sys
a, b = sys.argv[1:2]
summ = int(a) + int(b)
print "sum is", summ

There is no need for str() when printing an integer. But you should use int() if you want to add a and b as integers.

Your slice indexing is wrong. It should be a, b = sys.argv[1:3]
David
`a, b = sys.argv[1:2]` will result in ValueError, because of slicing rules.
SilentGhost
The major issue here is not string vs. int. The OP's original error ("list out of range") most likely comes from not passing arguments to the program.
codeape
@codeape, surely while this is the error, it's not an error in code logic, the main problem OP has is about adding those two numbers, and their type passed from command line.
SilentGhost
+3  A: 

The error list index out of range means that you are trying to access a list item that is outside the bounds 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 either sys.argv[1] or sys.argv[2].

Make sure you actually pass something to the program from the command line.

codeape
Beat me to it by 22 seconds. Yeah, I bet this is the actual problem.
Daniel Pryden
A: 

If your error is "list index out of range", then the problem is that your list doesn't have enough items. Which list? The only list you're using is sys.argv, so to populate it, you need to pass more items on the command line.

Alternatively, check for the length of the argument list with len(sys.argv) and prompt interactively (e.g. using raw_input()) to get the values if they're not in sys.argv.

Daniel Pryden
+3  A: 

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 a little faster in this instance.

>>>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
David
Why use map, when it is shorter to write `sum(int(arg) for arg in sys.argv[1:])`
kaizer.se
@kaiser.se: The inefficiency in David's answer is in using `sum(i for i in some_sequence)` instead of `sum(some_sequence)` ... if "shorter" is required, try 'sum(map(int, sys.argv[1:]))`
John Machin
@john you're right, that was silly. Updated the snippet.
David
map is still inefficient as it creates a new list as intermediate value. It can be argued that the generator expression is far more pythonic, but YMMV.
kaizer.se
And if it's anything that we want to teach newcomers to Python, it's generator expressions that have a very broad general use, while map is not so general.
kaizer.se
@kaizer.se I see your point, but in this case map is slightly more efficient.In [2]: t1 = timeit.Timer("sum(map(int,['3','5','7','9']))")In [3]: t2 = timeit.Timer("sum(int(i) for i in ['3','5','7','9'])")In [4]: t1.timeit()Out[4]: 3.0187220573425293In [5]: t2.timeit()Out[5]: 3.4699549674987793
David
@kaizer.se but I'll update the snippet with the generator method too :)
David
ok nice. I timed the imap version as well, and it is almost as fast as map `from itertools import imap; sum(imap(int,xrange(100)))`
kaizer.se
A: 

If you wish to sum the numbers as floating points number use "float" instead of "int", like 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 that you could obtain seemingly "strange" results about which there is a wealth of documentation on the web.

Francesco
A: 

Thanks to every one. I got the answer

for i in range (1,51): if i%5==0: print i,"\n" else: print i,

geeta