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)
word_count()
Output:
Enter a string: python is my fav programming language
The number of words in the string is: 6
Explanation:
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:
- The
word_count()
function is defined with no parameters. - The user is prompted to enter a string using the
input()
function and the string is stored in thetext
variable. - The
split()
function is used to split thetext
variable into a list of words using whitespace as the delimiter. The resulting list is stored in thewords
variable. - The
len()
function is used to determine the number of words in thewords
list, and the resulting value is stored in thecount
variable. - The number of words is printed to the console using the
print()
function and the string formatting technique to display the value of thecount
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.