Python Program — Count Occurrences of a Word Using a Function
Write a Python Program containing a function FindWord(STRING, SEARCH), that accepts two arguments : STRING and SEARCH, and prints the count of occurrences of SEARCH in STRING. Write appropriate statements to call the function.
For example, if
STRING = “Learning history helps to know about history with an interest in history” and
SEARCH = ‘history’,
The function should display:
The word history occurs 3 times.
In this program, we create a function FindWord(STRING, SEARCH) that accepts two arguments — a sentence (STRING) and a word to search (SEARCH). The function counts how many times the given word appears in the string and prints the result.
This type of question is important for Class 12 Computer Science (Python), Functions & String Handling concepts.
🔹 Problem Statement
Write a Python function FindWord(STRING, SEARCH) that prints the count of occurrences of SEARCH in STRING.
Example
STRING = "Learning history helps to know about history with an interest in history"
SEARCH = "history"
Output:
The word history occurs 3 times.
✅ Python Program
def FindWord(STRING, SEARCH):
words = STRING.split() # Convert string into list of words
count = 0
for w in words:
if w.lower() == SEARCH.lower(): # case-insensitive comparison
count += 1
print("The word {SEARCH} occurs", count, "times.")
# ---- Function Call ----
STRING = "Learning history helps to know about history with an interest in history"
SEARCH = "history"
FindWord(STRING, SEARCH)
📝 Explanation
STRING.split()breaks the sentence into individual words- A loop counts how many times
SEARCHappears .lower()ensures matching is case-insensitive- Finally, the function prints the total count
🖥 Sample Output
The word history occurs 3 times.
🎯 Learning Outcome
This program helps students understand:
- User-defined functions
- String splitting
- Case-insensitive comparison
- Counting occurrences in text
It is an important CBSE Class 12 Python function program frequently asked in exams and practical files.
In every board examination cbse must asked the programming questions based on CBSE Class 12 Functions, File Handling, Stack and Python MySQL connectivity Questions