Skip to content

Commit 3819d50

Browse files
authored
Create wordcounter.md
1 parent 5046ee0 commit 3819d50

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

contrib/mini-projects/wordcounter.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Word Counter
2+
This project counts the number of words entered in the input sentence and give the number (count) of words in output.
3+
Each element present in the text will be considered a letter, and a group of letters with a space will be considered a word.
4+
It takes string as input from user, and counts the total number of words in the string. This count is displayed as output.<br>
5+
Sample Input:- Harry likes Open Source<br>
6+
Sample Output:- 4<br>
7+
Explaination:- The above sentence contain 4 words.<br>
8+
9+
# Components of the code:
10+
The provided code defines a Python function count_words(sentence) aimed at counting the number of words in a given sentence. Here's a step-by-step description:
11+
12+
- ### Function Definition:
13+
14+
The code begins with the definition of a function named count_words.
15+
It takes a single parameter sentence, representing the input string whose words are to be counted.
16+
- ### Splitting the Sentence:
17+
18+
Within the function, the input sentence is split into individual words using the split() method.
19+
The split() method divides the string into substrings based on whitespace characters (spaces, tabs, and newline characters) by default.
20+
- ### Counting Words:
21+
22+
The code determines the number of words in the sentence by calculating the length of the list generated from splitting the sentence.
23+
The len() function is utilized to compute the length of the list, which corresponds to the number of words in the sentence.
24+
- ### Returning the Count:
25+
26+
After determining the word count, the function returns this value.
27+
- ### Example Usage:
28+
29+
The script prompts the user to input a sentence using the input() function.
30+
It then calls the count_words function, passing the user's input as an argument, and stores the returned word count in the variable number_of_words.
31+
Finally, it prints out the number of words in the sentence.
32+
33+
def count_words(sentence):
34+
# Split the sentence into words
35+
words = sentence.split()
36+
37+
# Count the number of words
38+
word_count = len(words)
39+
40+
return word_count
41+
42+
# Example usage:
43+
sentence = input("Enter a sentence: ")
44+
number_of_words = count_words(sentence)
45+
print("Number of words:", number_of_words)

0 commit comments

Comments
 (0)