Practice Question 29
In this question, we will learn how to write a function that scans a report and counts how many individual lines mention the word “success”. This is a common task in log analysis and data filtering.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
We use a list-based approach to ensure we check every line individually:
-
The
readlines()Method: We read the entire file into a list where each element is one line from the file. -
The
inOperator: This is a membership operator that checks if a string exists anywhere inside another string. -
Case Insensitivity: Since “Success” and “success” are different to a computer, we use
.lower()to make the search uniform. -
The Counter: If the word exists in the line, we increment the count.
Let’s Code as per the above logic :
def countLinesWithWord():
f = open("report.txt", "r")
linelist = f.readlines()
count = 0
for line in linelist:
# Using .lower() ensures we find "Success", "SUCCESS", and "success"
if "success" in line.lower():
count += 1
f.close()
return count
# To call the function and see the result:
print("Number of lines containing 'success':", countLinesWithWord())
Important Notes for Students
As a teacher, I want you to focus on these three key points so you don’t lose marks:
-
Line-Based Counting: This code counts the line. If “success” appears twice on the same line, the
countonly goes up by 1 for that line. -
readlines()vsread(): Whileread()gives you one giant string,readlines()gives you a structured list of lines, which is perfect when the question specifically asks you to “count lines.” -
Substring Match: The
inoperator finds the word even if it’s part of another word (like “successfully”).
Teacher’s Secret Tip for Exams:
When searching for a word in a line, there are usually 3 specific cases the examiner might ask you to handle:
-
Starts with:
if line.lower().startswith("success"): -
Ends with:
if line.lower().endswith("success"): -
Anywhere in between:
if "success" in line.lower():(This is what we used above!)
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]