Search code examples
pythonargv

Python: invalid literal for int() with base 10: 'a'


import sys

a =int( sys.argv[1])

print "\nArguments -->",a , sys.argv[2]

print "\nNo of Argu ",  len(sys.argv), "\n"

print str(sys.argv)

command window output which i give is:

python testfunction.py a sf df sf

Whenevr the first argument is taken as 'a', it shows the error -->

invalid literal for int() with base 10: 'a'

Newbie to python. PLease provide the solution for how to handle this without try except

Also

When i dont give ant argument i should handle that too

Command window outout which i give:

python testfunction.py

Error: IndexError: list index out of range


Solution

  • I am not quite sure if you know what you are doing but let me clarify this for you:

    a =int( sys.argv[1])
    

    you expect your first argument to be of type integer. Which obviously is not the case since you call your script with the following arguments:

    a sf df sf
    

    Python trys to convert your first argument to an integer. Which fails.

    A simple simple fix would be to make sure the first argument is an integer:

    if sys.argv[1].isdigit():
        a = int(sys.argv[1])
    else:
        print "First argument is not a digit"
        sys.exit(1)
    

    Or surrond this with a try except block (which i would to)

    try:
       a = int(sys.argv[1])
    except ValueError:
       print "Stupid user, please enter a number"
       sys.exit(1)