Practice Question 25
In this question, we will learn how to write a function that scans an article and counts the total number of common punctuation marks (., ,, !, ?, :, ;).
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To count these symbols efficiently, we treat the file as a stream of individual characters:
-
Read Character by Character: We use
f.read()to get the entire file content. -
Define the Target Set: We create a string variable
marks = ".,!?:;"containing all the symbols we want to count. -
The Comparison: For every character in the file, we check if it is “in” our
marksstring. -
The Counter: If the character exists in our defined set, we increment the count.
Let’s Code as per the above logic :
def countPunctuation():
f = open("article.txt", "r")
data = f.read()
# Define the set of punctuation marks we are looking for
marks = ".,!?:;"
count = 0
for alpha in data:
if alpha in marks:
count += 1
f.close()
return count
# To call the function and see the result:
print("Total number of punctuation marks:", countPunctuation())
Important Notes for Students
As a teacher, I want you to pay close attention to these points, as they are where most students make mistakes in exams:
-
-
The Power of
in: Usingif char in marksis much cleaner than writingif char == '.' or char == ','.... It makes your code faster and easier for the examiner to read. -
read()for Characters: Since punctuation is a character-level detail,f.read()is the most appropriate method here. -
Extending the Logic: If you need to count other symbols like
@,#, or$, you simply add them to themarksstring. No other part of the code needs to change!
-
Teacher’s Secret Tip for Exams:
Python actually has a built-in collection of all punctuation marks! You can use import string and then check if char in string.punctuation. Using this in a practical exam shows you have advanced knowledge of Python modules!
Want to practice more? If you found this helpful, I have compiled a full list of 30 practice problems just like this one. Each question focuses on a different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set
Exam Special Recommendation: If you are studying in 12th class and preparing for your board exam, then go for the “Computer Science with Python Sample Paper Book“. It contains 3 previous years’ papers and 7 practice papers solved strictly as per the CBSE pattern. Click here to purchase your copy!