In python-data-analysis-basics/3/ Creating a function to calculate avarage for a given data list

Screen Link:

My Code: <!–# Creating a function to calculate avarage for a given data list.
def avg_comments(data):

total_commnets = 0
for row in data:
    num_comments = int(row[4])
    total_commnets + num_comments
    
avg = total_comments/ (len(data))
return avg

avg_ask_comments = avg_coments(ask_posts)
avg_show_comments = avg_coments(show_posts)

print(avg_ask_comments)
print(avg_show_comments)–>

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

What I expected to happen:

In Guided Project: Exploring Hacker News Posts page 4 where I needed to calculate the average number of comments for posts beginning with Ask HQ and Show HQ.

Instead of writing the same code for two different list, I though of creating a method/Function avg_comments(data). When a Call the functiion avg_comments(data) as…

avg_ask_comments = avg_coments(ask_posts)
avg_show_comments = avg_coments(show_posts)

print(avg_ask_comments)
print(avg_show_comments)

Instead of giving me the average for lists it runs in to error

What actually happened:

NameErrorTraceback (most recent call last)
<ipython-input-44-2c24a3d54edb> in <module>()
     12     return avg
     13 
---> 14 avg_ask_comments = avg_coments(ask_posts)
     15 avg_show_comments = avg_coments(show_posts)
     16 

NameError: name 'avg_coments' is not defined

<

Hi @vicky.mevawala, Check that you spell “comments” the same way universally throughout. At some places you spelled it as “coments” and “commnets”… Hope this helps! :grin:

1 Like

Thanks Victor. Code run now without error ```
name ‘avg_coments’ is not defined

Its has another issue like the output in 0.0. Let check what the issue first.

@vicky.mevawala,

Ensure you define the function using the def keyword and also ensure that the spellings for each variable are the same throughout.
After effecting the corrections, your function should look like this:

def avg_comments(data):
    total_comments = 0
    for row in data:
        num_comments = int(row[4])
        total_comments += num_comments
    avg = total_comments/ (len(data))
    return avg

avg_ask_comments = avg_comments(ask_posts)
avg_show_comments = avg_comments(show_posts)

print(avg_ask_comments)
print(avg_show_comments)

I hope this helps.

2 Likes

Thanks doyinsolamiolaoye, Yes the issue was with the spellings of comments.

1 Like