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?
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?
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.
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()