Practice Question 3
In this post, we will learn how to write a function that finds all the numerical digits in a text file and calculates their sum. This is a fantastic exercise for learning how to extract numbers from a mix of text and symbols
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
When we read a file, everything—including numbers—is treated as a “string.” To add them up, we need to follow these steps:
-
Open & Read: We open
letter.txtand read the content. -
Identify Digits: We look at every character and check if it is a number using
.isdigit(). -
Type Conversion: Since you cannot mathematically add a “string” number, we convert the character into an integer using
int(). -
Running Total: We add that integer to a
total_sumvariable.
Let’s Code as per the above logic :
def sumOfDigits():
f = open("letter.txt", "r")
data = f.read()
total_sum = 0
for alpha in data:
if alpha.isdigit():
total_sum += int(alpha)
f.close()
return total_sum
# To call the function and see the result:
print("The sum of all digits is:", sumOfDigits())
Important Notes for Students
As a teacher, I want you to pay close attention to these two points, as they are where most students make mistakes in exams:
-
Why use
int()? In Python, the character'5'from a file is a string, not a number. If you try to add it withoutint(), Python will give you a “TypeError.” Converting it to an integer allows us to perform addition. -
The
isdigit()Method: This is a built-in string method that returnsTrueonly if the character is a digit (0-9). It automatically ignores alphabets, spaces, and special symbols for us. -
Variable Initialization: Always remember to set your
total_sum = 0outside the loop. If you put it inside the loop, the sum will reset to zero every time a new character is read!
Teacher’s Secret Tip for Exams:
This logic is very flexible! Depending on what the question asks, you only need to change one line:
-
To Count Digits: Use
total_sum += 1instead of adding the value. -
To Display Digits: Simply use
print(alpha)inside theifcondition. -
To Sum Digits: Use
total_sum += int(alpha)as shown in the solution above.
Learning how to tweak one logic for different goals is the secret to becoming a great programmer!
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!