Case study: Word Counting System
We will create a program that can count the number of words in a piece of text. The steps are as follows:
- Create a function called
count_words()
that will accept a string as input. - Within the function, create a variable called
counter
with an initial value of 0. This variable will be used to store the number of words in the string. - Split the string into words using the
split()
method. This method will split the string into a list of words separated by spaces. - Use a for loop to check each word in the split list. If the word is not an empty string (“”), add 1 to the
counter
variable. - After the for loop has finished running, return the value of the
counter
variable as the output of the function.
Here is the implementation of the program:
def count_words(text):
counter = 0
words = text.split()
for x in words:
if x != "":
counter += 1
return counter
print(count_words("This is an example sentence.")) # Output: 8
print(count_words("How are you?")) # Output: 5
print(count_words(" ")) # Output: 0
The
count_words()
function accepts a string as input and creates a variable calledcounter
that is initialized to 0. This variable will be used to store the number of words in the string.The string is then split into a list of words using the
split()
method, which separates the words by spaces.A for loop is used to iterate through each word in the
words
list. If the current word is not an empty string, thecounter
variable is incremented by 1.After the for loop has finished running, the value of the
counter
variable is returned as the output of the function.So the function counts the number of words in the input string by iterating through each word in the string, incrementing the
counter
variable for each non-empty word, and returning the final value of thecounter
variable.
Now we understand how to use a for loop to count the number of words in a piece of text. Happy trying!