Practice Question 1
In this post, we will look at how to read a text file and count the number of consonants. This is a very common logic used in Board Exams and college practicals to test your understanding of strings and file handling.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
-
Open & Read: We first open
story.txtand read the entire content into a single string. -
Filter Alphabets: A file contains spaces, numbers, and symbols. We only care about letters, so we use
.isalpha(). -
Check for Consonants: If a letter is NOT an ‘a, e, i, o, u’, then it must be a consonant!
Let’s Code as per the above logic :
def countConsonants():
f = open("story.txt", "r")
data = f.read()
count = 0
for alpha in data:
if alpha.isalpha():
if alpha not in 'aeiouAEIOU':
count += 1
f.close()
return count
# To call the function:
print("Total number of consonants:", countConsonants())
Important Notes for Students
As a teacher, I want you to focus on these three key points so you don’t lose marks:
-
The
isalpha()Check: This is the most important step. A text file often has spaces, full stops, and numbers. If you don’t useisalpha(), your code might count a symbol as a consonant. Always check if it’s a letter first! -
Handling Case Sensitivity: Notice that we check against
'aeiouAEIOU'. If you only check against lowercase vowels, your program will accidentally count uppercase ‘A’, ‘E’, ‘I’, ‘O’, or ‘U’ as consonants. -
Closing the File: Even though some systems close the file automatically, always write
f.close()at the end of your function. In a board exam, forgetting this can sometimes cost you half a mark.
Teacher’s Secret Tip for Exams:
If the question asks you to count “vowels” instead of “consonants,” you just need to change one line! Instead of if alpha not in 'aeiouAEIOU':, you would simply write if alpha in 'aeiouAEIOU':. The rest of the logic stays exactly the same.
Want to practice more? If you found this helpful, I have compiled a full list of 15 practice problems just like this one. Each question focuses on different logic to help you become a pro at File Handling.
Click here to view the full 30-Question Practice Set