Practice Question 16
In this question, we will learn how to write a function that reads a text file and counts the total number of Uppercase (Capital) letters. This is a classic “Character-based” file handling problem often asked in Class 12 CS practicals and theory exams.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To count specific types of characters, we must examine the file character-by-character. Here is the teacher’s breakdown:
-
Read the Content: We use
f.read()to get the entire content ofmessage.txtas a single string. -
The Loop: We use a
forloop to iterate through every single character (including spaces and symbols). -
The condition: We use the built-in string method
.isupper(). This method returnsTrueif the character is a capital letter andFalseotherwise. - The Counter: Every time
.isupper()is true, we increment ourcountvariable.
Let’s Code as per the above logic :
def countUppercase():
f = open("message.txt", "r")
data = f.read()
count = 0
for alpha in data:
if alpha.isupper():
count += 1
f.close()
return count
# To call the function and see the result:
print("Total Uppercase Letters:", countUppercase())
Instead of using built-in methods, we will use character comparison logic, which is often a requirement in computer science logic tests.
The Logic (How it works)
In Python, characters can be compared using < and > because every character has a numeric value (ASCII/Unicode).
-
Read content: We read the entire file into a string.
-
The Range Check: We loop through each character. If a character is greater than or equal to
'A'AND less than or equal to'Z', it falls exactly in the range of uppercase English alphabets. -
The Increment: If the character is within this range, our counter goes up.
def countUppercase():
f = open("message.txt", "r")
data = f.read()
count = 0
for alpha in data:
# Check if the character falls between 'A' and 'Z'
if alpha >= 'A' and alpha <= 'Z':
count += 1
f.close()
return count
# To call the function and see the result:
print("Total Uppercase Letters:", countUppercase())
Important Notes for Students
Keep these exam tips in mind:
-
read()vsreadlines(): For character-level tasks (like counting letters or vowels),f.read()is the best choice because it treats the whole file as one long string, making it easy to loop through every character. -
The
isupper()Method: This method only returnsTruefor ‘A’ through ‘Z’. It correctly returnsFalsefor numbers, spaces, and special symbols like@or#. -
Return vs Print: Notice the function returns the count. In exams, if the question says “Write a function that returns…”, make sure to use the
returnkeyword instead of just printing it inside the function. -
The Comparison Advantage: This logic is “Language Independent.” Even if you were coding in C++ or Java, the logic
alpha >= 'A' and alpha <= 'Z'would remain the same. -
Case Sensitivity: Ensure you use capital ‘A’ and capital ‘Z’. If you accidentally use lowercase ‘a’, the range will include many symbols you don’t want!
-
The Variable Name: You used
alphaas your loop variable. This is good practice as it makes the code readable and implies you are looking for alphabets.
Teacher’s Secret Tip for Exams:
If the examiner asks you for Lowercase letters using this same logic, simply change the condition to: if alpha >= 'a' and alpha <= 'z':. To check for Digits, use: if alpha >= '0' and alpha <= '9':.
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!