Practice Question 8
In this question, we will learn how to write a function that scans a text file and identifies the longest word present in it. This logic is very similar to finding the “Largest Number” in a list.
The Logic (How it works)
Before writing the code, let us first understand the logic behind the solution.
To find the longest word, we need to compare the lengths of all words one by one. Here is the step-by-step logic:
-
Open & Split: We open
paragraph.txtand use.split()to break the text into a list of words. -
Initialize a Leader: We create a variable (let’s call it
longest) and set it to an empty string"". -
The Comparison Loop: We loop through every word in the list.
-
Update the Winner: If the length of the current word is greater than the length of our current “leader” (
longest), we replace the leader with the new word. -
Result: After the loop finishes, the variable
longestwill hold the word with the most characters.
Let’s Code as per the above logic :
def findLongestWord():
f = open("paragraph.txt", "r")
data = f.read()
wordlist = data.split()
longest = "" # This will store our result
for word in wordlist:
# Check if current word is longer than our previous champion
if len(word) > len(longest):
longest = word
print("The longest word in the file is:", longest)
f.close()
# To call the function:
findLongestWord()
Important Notes for Students
As a teacher, I want you to keep these points in mind for your Board Practical or Viva:
-
The
len()Function: This is the heart of the code. It calculates the number of characters in a string. -
Initial Value: We start
longestas an empty string ("") because any word we find will be longer than zero characters, ensuring the first word always becomes our first “leader.” -
Multiple Longest Words: If two words have the same maximum length, this specific code will keep the first one it found. If you want the last one, you would change the condition to
if len(word) >= len(longest):.
Teacher’s Secret Tip for Exams:
f the examiner asks you to find the Shortest Word instead of the longest, just initialize shortest = wordlist[0] and change the condition to if len(word) < len(shortest):. The logic remains the same—just reversed!
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!