Invalid literal for int() with base 10: 'H'

Hi All,

i am trying to convert string values into integer but i am unable to do so. Kindly help me out.
attaching you the code and error screenshot.

Code :-

Calculate the average number of comments Ask HN posts receive.

total_ask_comments = 0

for post in ask_posts:
total_ask_comments += int(post[4])

avg_ask_comments = total_ask_comments / len(ask_posts)
print(avg_ask_comments)

total_show_comments = 0

for post in show_posts:
total_show_comments += int(post[4])

avg_show_comments = total_show_comments / len(show_posts)
print(avg_show_comments)

Error :-

ValueErrorTraceback (most recent call last)
in ()
3
4 for post in ask_posts:
----> 5 total_ask_comments += int(post[4])
6
7 avg_ask_comments = total_ask_comments / len(ask_posts)

ValueError: invalid literal for int() with base 10: ‘H’

1 Like

Hi savigyasingh007,

Please format your code for the sake of readability by putting it inside backticks like so:

```
<your code>
```

Also, please include a link to the screen where you are having this problem.

People will be much more likely to help you if you make it easier for them to do so!

Hi

Be sure that info in post[4] could be cast to int .
I can generate the error "ValueError: invalid literal for int() with base 10: ‘H’ " if i do something like that :

value = int('H')
2 Likes

The error message invalid literal for int() with base 10 would seem to indicate that you are passing a string that’s not an integer to the int() function . In other words it’s either empty, or has a character in it other than a digit.

You can solve this error by using Python isdigit() method to check whether the value is number or not. The returns True if all the characters are digits, otherwise False .

if val.isdigit():

The other way to overcome this issue is to wrap your code inside a Python try…except block to handle this error.

Python2.x and Python3.x

Sometimes the difference between Python2.x and Python3.x that leads to this ValueError: invalid literal for int() with base 10 .

With Python2.x , int(str(3/2)) gives you “1”. With Python3.x , the same gives you (“1.5”): ValueError: invalid literal for int() with base 10: “1.5”.

Not sure if you’ve already figured this out, but saw another post that possibly fixes your issue. If you mistyped your code and appended the title, then you’ll run into the issue of trying to typecast your title into an integer which won’t work. If your code shows this, then fix it to append the entire row for each iteration and it should fix your average comment count step.

Older post that solves it