How does one solve "invalid literal for int() with base 10: 'H'" am on guided project two and am trying convert number_comments into an integer

Screen Link:
https://app.dataquest.io/m/356/guided-project%3A-exploring-hacker-news-posts/4/calculating-the-average-number-of-comments-for-ask-hn-and-show-hn-posts

My Code:

total_ask_comments = 0
for row in ask_posts:
num_comments = int(row[4])
total_ask_comments + num_comments

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

Replace this line with your code

What I expected to happen:
to convert number_comments into an integer

What actually happened:

ValueErrorTraceback (most recent call last)
in ()
1 total_ask_comments = 0
2 for row in ask_posts:
----> 3 num_comments = int(row[4])
4 total_ask_comments + num_comments
5

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

Replace this line with the output/error

@johnmaina1994, welcome to the community!

First of all, your 4th line of code should be total_ask_comments += num_comments.

The error message in your code ValueError: invalid literal for int() with base 10: ‘H’ is raised whenever we call int() function with a string argument that can not be parsed as an integer.
At line 3 of your code, you called the int() function on row[4] but it contains a string "H" that can’t be parsed into an integer.

Be sure that row[4] only contains values that can be parsed into an integer:

The following are totally acceptable in python:

  • passing a string representation of an integer into int()
  • passing a float into int()

I hope this helps.

Thanks let me check my code

Hello @johnmaina1994,

Has this problem been solved?

If you are still stuck there, check the code you used to make your show_posts , ask_posts , and other_posts lists: The correct code block should be:

for row in hn:
    title = row[1]
    if title.lower().startswith("ask hn"):
        ask_posts.append(row)
    elif title.lower().startswith("show hn"):
        show_posts.append(row)
    else:
        other_posts.append(row)

Ensure you append the row to the list of lists and not title. If you append title, the element in the 4th index i.e row[4] would return a string value "H" and this can not be parsed into an integer as I already explained in my first reply. It is the element in the 4th index of the row that you need to calculate your total_ask_comments.