share
Stack OverflowWord count from the user
[-3] [1] T.Drummonds
[2017-11-11 01:29:33]
[ python python-3.x ]
[ https://stackoverflow.com/questions/47233419/word-count-from-the-user ]

I'm completely new to Python and coding in general. I am needing to write a code that allows the user to input many lines and when they are finished writing their multiple sentences, they enter a single period to stop the program and the program will then tell the user how many words were inputted. How would I go about doing this?

Here is what I have so far:

print("Enter as many lines of text as you want.")
print("When you're done, enter a single period on a line by itself.")

while True:
    print("> ", end="")
    line = input()
    if line == ".":
        break
    totalWords = line.split()
    newWords = totalWords.append(line)
wordCount = len(newWords)
print("The number of words entered:" , wordCount, "")
(2) "Questions" of the type I want X and who helps me do not like us in SO, here you must show what you have tried and what problems you have had, so we will help you with advice or possible solutions - eyllanesc
(2) Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it. - stackoverflow.com/help/on-topic - skrx
(1) I recommend you read the following to improve your question: How do I ask a good question? - eyllanesc
[0] [2017-11-11 02:14:11] Q Yang [ACCEPTED]

You should set content out of loop.

content = []
while True:
    line = input()
    if line == ".":
        break
    words = line.split()
    content.append(words)

words_list = [item for sublist in content for item in sublist]
print(len(words_list))

Besides, Most functions that change the items of sequence/mapping does return None. So newWords = totalWords.append(line) will always return None.


Thank you a ton, this has helped me a ton. I've been stressing over this problem for the last 3-4 hours. - T.Drummonds
1