Reputation: 17
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
Reputation: 9681
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)
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
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
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