Python Word Count Program

In this source code example, we will write a Python word count program that counts the number of words in a given input string.

Python Word Count Program

Here is a program in Python that counts the number of words in a string, along with an explanation:
def word_count():
    text = input("Enter a string: ")
    words = text.split()
    count = len(words)
    print("The number of words in the string is:", count)



Enter a string: python is my fav programming language
The number of words in the string is: 6


This is a Python function called word_count() that counts the number of words in a string entered by the user.

Here is a step-by-step explanation of how the code works:

  1. The word_count() function is defined with no parameters.
  2. The user is prompted to enter a string using the input() function and the string is stored in the text variable.
  3. The split() function is used to split the text variable into a list of words using whitespace as the delimiter. The resulting list is stored in the words variable.
  4. The len() function is used to determine the number of words in the words list, and the resulting value is stored in the count variable.
  5. The number of words is printed to the console using the print() function and the string formatting technique to display the value of the count variable.

When the function is called at the bottom of the code with word_count(), the user will be prompted to enter a string. Once the user enters a string, the function will split the string into words, count the number of words, and print the result to the console.