Katerina
Katerina

Reputation: 17

Issue with program that counts the average word length

I am very new to Python so I am only familiar with some very basic functions and I am doing an exercise on loops. I need to build a program that counts average word length. Here is my code:

sentence = input ("Give your sentence:")
words = len(sentence.split())
print(words)
characters = 0
for word in words:
    characters += len(word)
    average_word_lengt = characters/words

It is giving me an error:

'int' object is not iterable

What does it mean and how can I make it work?

Upvotes: 2

Views: 116

Answers (3)

s3dev
s3dev

Reputation: 9681

The main issue:

The following statement returns words as an integer. Therefore you cannot iterate.

words = len(sentence.split())

Given that you want to iterate over your list of words, try this instead:

words = sentence.split()
n_words = len(words)

In more detail:

Here is an updated and working version of your code, using the example above:

sentence = input("Give your sentence: ")
# Updated here -->
words = sentence.split()
n_words = len(words)
# <--
print(words)
characters = 0
for word in words:
    characters += len(word)
    average_word_length = characters/n_words  # <-- and here.

If you'd like to take this a step further using a syntax called list comprehension (which is very useful!), here is another example:

words = input("Give your sentence: ").split()
avg_len = sum([len(w) for w in words])/len(words)

print('Words:', words)
print('Average length:', avg_len)

Upvotes: 2

D. Seah
D. Seah

Reputation: 4592

you cannot iterate on length. I guess you need to first get all string len; get the sum and then get average

import functools

sentence = input("Give your sentence:")
word_lens = list(map(lambda x: len(x), sentence.split()))
sums = functools.reduce(lambda x, y: x + y, word_lens, 0)
print(round(sums / len(word_lens)))

or

sentence = input("Give your sentence:")
word_lens = list(map(lambda x: len(x), sentence.split()))
sums = 0
for l in word_lens:
    sums += l
print(round(sums / len(word_lens)))

Upvotes: 1

Jaipi
Jaipi

Reputation: 50

You can simply iterate the string directly

sentence = input ("Give your sentence:")
word_count = {} #dictionary to store the word count
for word in sentence:
    if word in word_count.items(): #check if word is in the dictionary
        word_count[word] +=1 #adds +1 if already is
    else:
        word_count[word] = 1 #adds the word on the dict
result=len(sentence)/len(word_count) #this will divide the total characters with total single characters
print(result)

Upvotes: 0

Related Questions