#3- Case Study | For Loop Using Python

NUR ARIF
2 min readJan 7, 2023

--

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:

  1. Create a function called count_words() that will accept a string as input.
  2. 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.
  3. Split the string into words using the split() method. This method will split the string into a list of words separated by spaces.
  4. 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.
  5. 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 called counter 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, the counter 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 the counter variable.

Now we understand how to use a for loop to count the number of words in a piece of text. Happy trying!

--

--

NUR ARIF
NUR ARIF

Written by NUR ARIF

Backend | Data Scraping | Machine Learning | Python Programming | Pentester

No responses yet