Practice Question 18
In this question, we will learn how to write a function that scans a text file and counts every word that begins with a vowel (A, E, I, O, U).
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
Instead of checking if word[0] == 'a' or word[0] == 'e' ..., we use a much cleaner “Membership” approach:
-
Define Vowels: Create a string or list containing all vowels in both lowercase and uppercase:
"aeiouAEIOU". -
Read and Split: Open
story.txtand break the content into a list of words. -
The First Character Check: For every word, look at
word[0]. -
The
inOperator: Check if that first character exists in our vowel string. If it does, increment the counter.
Let’s Code as per the above logic :
def countVowelWords():
f = open("story.txt", "r")
data = f.read()
wordlist = data.split()
vowels = "aeiouAEIOU"
count = 0
for word in wordlist:
# Check if the first character of the word is in the vowel string
if word[0] in vowels:
count += 1
f.close()
return count
# To call the function and see the result:
print("Number of words starting with a vowel:", countVowelWords())
Important Notes for Students
- Case Sensitivity: In files, “Apple” starts with a vowel, and so does “apple”. By defining your vowels as
"aeiouAEIOU", you ensure you catch both cases. - String Indexing:
word[0]always targets the start of the word. Make sure the file isn’t empty, or add a check to ensure thewordhas a length greater than 0 to avoid errors. - The
inOperator: This is one of Python’s most powerful features. It’s faster and much more readable than using multipleorconditions.
Teacher’s Secret Tip for Exams:
If the question asks you to count words starting with a Consonant, simply use the not in operator: if word[0] not in vowels and word[0].isalpha():. (We add .isalpha() to make sure we don’t count numbers or symbols as consonants!)
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!