Error: ValueError: invalid literal for int() with base 10

Question:

I am a newbie Python. When i am trying execute the below code watching this Video, i got an error. What to understand what is the error, why it is coming and how to over come it?

import sys
x = int(sys.argv[1])

Error:

x = int(sys.argv[1])
IndexError: list index out of range

Than i started my Index value from ‘0’.
Code:

import sys
x = int(sys.argv[0])

Error:

x = int(sys.argv[0])
ValueError: invalid literal for int() with base 10:
Asked By: Developer

||

Answers:

Looks like you are running that code from Pycharm itself, And pycharm doesn’t pass those argv for you, and hence you are getting ListIndex error.To resolve this, You need to start your cmd and then navigate to the directory where your file is and then.

python <filename.py> arg1 arg2

where arg1 arg2 can be anything, So long as you handle them correctly in your script.

x = int(sys.argv[0])
ValueError: invalid literal for int() with base 10:

This happened because PyCharm passes the name of the file as argv[0]. And in your code you are trying to convert the name of the file into an int which results in this error.

x = int(sys.argv[1]) Wont work because PyCharm did not pass any values apart from the name of file at argv[0]. So argv[1] doesn’t exist and Therefore you get the ListIndex error.

Answered By: Vineeth Sai

As with all problems, break it down into smaller chunks.

First, run just sys.argv
You will see it is a list with an empty string. This means the out of index error is obvious because there is no item at a second index.

Next, you cannot use an empty string as an index with a list. That would be your second error.

Answered By: dfundako
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.