Practice Question 17
In this question, we will create a function that filters a text file to find and display words like “Python3”, “Win10”, or “Sector7G”—words that contain at least one numeric digit.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To find a digit inside a word, we have to look at the characters one by one. Here is the step-by-step breakdown:
-
Read and Split: We open
data.txtand split it into a list of words. -
The Outer Loop: We pick one word at a time from the list.
-
The Inner Loop: We look at every character inside that specific word.
-
The
isdigit()Check: If we find any character that is a digit, we print the word and break the inner loop (because we only need one digit to qualify).
Let’s Code as per the above logic :
def displayNumericWords():
f = open("data.txt", "r")
data = f.read()
wordlist = data.split()
print("Words containing at least one digit:")
for word in wordlist:
for alpha in word:
if alpha.isdigit():
print(word)
break # Stop checking this word once a digit is found
f.close()
# To call the function:
displayNumericWords()
Important Notes for Students
-
The
breakKeyword: This is very important! If a word is “Agent007”, it has three digits. Withoutbreak, the program would print “Agent007” three times.breakensures it is printed only once. -
isdigit()Method: This built-in function returnsTrueif a character is a number (0-9) andFalseif it is a letter or symbol. -
Nested Loops: This problem is a classic example of using a loop inside a loop. The first loop handles words, and the second loop handles characters.
Teacher’s Secret Tip for Exams:
If the examiner asks you to count how many such words exist instead of displaying them, simply replace print(word) with a counter like count += 1. This structure is very flexible!
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!