Programs · Program 8-1
Q.Program 8-1: Write a program with a user defined function to count the number of times a character (passed as argument) occurs in the given string.
Puducherry CbseNCERTSubjective· 3mImportance★★★★★est
15% · 2/13 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →A user-defined function receives the character and the string, walks the string with a for loop, and increments a counter each time the current character equals the target — a linear search that counts instead of stopping.
Idea. Counting occurrences is the simplest membership pattern: examine every character exactly once and keep a tally. Wrapping it in a function makes it reusable for any (character, string) pair — the two are passed as arguments.
def charCount(ch, st):
"""Count the number of times character ch occurs in string st."""
count = 0
for character in st:
if character == ch:
count += 1
return count
# main program
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch, st)
print("Number of times character", ch, "occurs in the string is:", count)
Key lines:
for character in st— visits each character of the string in order; no index bookkeeping needed.if character == ch: count += 1— the tally grows only on an exact (case-sensitive) match.- The function returns the count; printing is left to the caller — good separation of logic and I/O.
Trace for st = "Today is a pleasant day", ch = 'a' — the counter changes at these positions:
| Match # | Where | count |
|---|---|---|
| 1 | Today | 1 |
| 2 | "…is a…" (the word a) | 2 |
| 3 | pleasant | 3 |
| 4 | pleasant | 4 |
| 5 | day | 5 |
Sample run …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.