In this blog post, we’ll walk through a simple Python program that counts the number of words in a sentence. This task is a great way to practice basic Python programming skills, including handling user input, splitting strings, and counting elements in a list.
What We’re Going to Do
- Take a Sentence from the User: We’ll get a sentence input from the user.
- Split the Sentence into Words: We’ll break the sentence into individual words.
- Count the Words: We’ll count how many words are in the sentence.
- Display the Result: We’ll print the number of words.
Python Code
Here’s the Python code for counting the number of words in a given sentence:
# Step 1: Take input from the user
sentences = input("Enter the sentence: ")
# Step 2: Split the sentence into words
words = sentences.split()
# Step 3: Count the number of words
number_of_words = len(words)
# Step 4: Print the number of words
print(number_of_words)
Explanation of the Code
- Taking Input:
- We use
input("Enter the sentence: ")
to ask the user to type in a sentence. This function captures the user’s input as a string and stores it in the variablesentences
.
- Splitting the Sentence:
sentences.split()
is used to split the input sentence into a list of words. Thesplit()
method divides the string at each whitespace (spaces, tabs, or newlines) by default.- For example, if the user enters
"Python is fun"
, thesplit()
method will produce the list["Python", "is", "fun"]
.
- Counting Words:
len(words)
calculates the number of elements in the listwords
. Each element in the list represents a word from the original sentence.- If the list is
["Python", "is", "fun"]
, thenlen(words)
will be3
.
- Printing the Result:
print(number_of_words)
displays the total number of words in the sentence.
Example Test Cases
Let’s test our program with a few examples:
- Example 1:
- Input:
"Hello world"
- Output:
2
- Explanation: The sentence
"Hello world"
contains 2 words:"Hello"
and"world"
.
- Example 2:
- Input:
"This is a test sentence"
- Output:
5
- Explanation: The sentence
"This is a test sentence"
has 5 words:"This"
,"is"
,"a"
,"test"
, and"sentence"
.
- Example 3:
- Input:
" Python programming "
- Output:
2
- Explanation: Even though the input has leading and trailing spaces, the
split()
method handles them gracefully, resulting in 2 words:"Python"
and"programming"
.
- Example 4:
- Input:
" "
(Just spaces) - Output:
0
- Explanation: When the input is just spaces, the
split()
method returns an empty list, resulting in a word count of 0.
Conclusion
Counting the number of words in a sentence is a fundamental task in text processing. With this simple Python program, you can easily count words in any sentence. By understanding how to handle user input, split strings, and count list elements, you’re building essential skills for working with text data in Python. Keep practicing with different inputs to reinforce your understanding!