Word Counter

This was surprisingly a lot simpler than what I thought it was going to be. However, although this is very simple, a word counter is useful because most websites which require the user to enter something often have a maximum word limit. This will mean that the user could use this word counter in order to make sure that they have not gone over the limit.

Attempt 1:

This was my first attempt however, it didn’t work as intended.

array = []
user_input = input("Enter your text ")
words = user_input.split
array.append(words)
print("Word Count:",len(array))

This didn’t work because when I used the append() function to add to the array, it added the whole text together rather than separately which meant that the word count displayed as 1

Test input: Hello this is a test
Expected output: Word Count: 5
Test output: Word Count: 1

Final Attempt

user_input = input(str("Enter your text "))
words = user_input.split() 
x = (len(words))
print("Word Count:",x)

The user_input is a variable which indicates that the user needs to input something. However, it is only a name and doesn’t actually preform the input() function. The input() function is used when the user needs to input either a string/strings or a numerical value. Here, I have used it to allow the user to type what words that they want to be counted. The next line uses the word variable which is simply just making a variable called (words) the same as what the user typed for their text. However, the .split() function separates each word individually which makes it a lot easier to count the words. I then assigned the variable (x) to the length of each word. Finally, I outputted the word count to the user.

Test input: Hello this is a test
Expected output: Word Count: 5
Test output: Word Count: 5