new to python here. I am trying to write a program that calculate the average word length in a sentence and I have to do it using the .split command. btw im using python 3.2
this is what I’ve wrote so far
sentence = input("Please enter a sentence: ") print(sentence.split())
So far i have the user enter a sentence and it successfully splits each individual word they enter, for example: Hi my name is Bob, it splits it into [‘hi’, ‘my’, ‘name’, ‘is’, ‘bob’]
but now I’m lost I dunno how to make it calculate each word and find the average length of the sentence.
Advertisement
Answer
In Python 3 (which you appear to be using):
>>> sentence = "Hi my name is Bob" >>> words = sentence.split() >>> average = sum(len(word) for word in words) / len(words) >>> average 2.6