-3

I want to do simple addtion using argv in python.

Here is my code:

import sys

x = int(sys.argv[1])
y = int(sys.argv[2])
z = x + y

print(z)

I am running this program in python 3.4, but it is throwing IndexError.

Any suggestions?

Ralf
  • 16,086
  • 4
  • 44
  • 68
Anish
  • 1
  • The IndexError means you didn't pass any command line arguments. See https://en.wikipedia.org/wiki/Command-line_interface#Arguments – Aran-Fey Aug 18 '18 at 12:12

2 Answers2

2

How are you trying to run your script? I ran "python3.6 sample.py 1 2" on my linux machine. That worked for me. Index error will be thrown out if you don't give enough arguments while you are trying to execute the code. As you mentioned sys.argv[2]. You must give atleast 2 arguments after the filename to run this code.

For example, if you run the code like "python3.6 sample.py 1" Index error will be thrown out.

  • when i am running this in command prompt ,it is working. But when i am running in IDLE python shell it is throwing that Index error. – Anish Aug 21 '18 at 13:03
1

The error indicates that your script did not get enough parameters that you are trying to access.

Try printing sys.argv to see what actually gets passed in.

Or you could build a more robust code:

import sys

def calc():
    print('argv:', sys.argv)

    try:
        x = int(sys.argv[1])
    except IndexError:
        print('no value for "x"')
        return
    except ValueError:
        print('value for "x" is not an integer')
        return

    try:
        y = int(sys.argv[2])
    except IndexError:
        print('no value for "y"')
        return
    except ValueError:
        print('value for "y" is not an integer')
        return

    z = x + y
    print('z: ', z)

if __name__ == '__main__':
    calc()
Ralf
  • 16,086
  • 4
  • 44
  • 68