Computer Science - Class 12
Solutions to CBSE Sample Paper - Computer Science Class 12

Write a function, longestWord() in Python that finds and displays the longest word in the text file named Book.txt 

Answer:

Answer by student

Function in Python that finds and displays the longest word in a text file - Teachoo.png

Detailed answer by teachoo

  • The code defines a function named longestWord that takes no parameters and finds and displays the longest word in the text file named Book.txt.
  • The function performs the following steps:
    • It opens the file in read mode using the open function and assigns the file object to a variable called file. This allows the function to access the contents of the file.
    • It initializes a variable called longest to an empty string . This variable will store the longest word found so far in the file.
    • It loops through each line in the file using a for loop . In each iteration, it assigns the current line to a variable called line .
    • It splits the line into a list of words using the split method . This method returns a list of strings that are separated by whitespace characters (such as spaces, tabs, or newlines) in the original string. For example, if line is “This is a sentence.”, then words will be [“This”, “is”, “a”, “sentence.”].
    • It loops through each word in the list using another for loop . In each iteration, it assigns the current word to a variable called word .
    • It checks if the length of the word is greater than the length of the longest word using the len function. This function returns the number of characters in a string. For example, len(“hello”) is 5. If the condition is True, it means that the current word is longer than the previous longest word.
    • It updates the longest word with the current word by assigning it to the variable longest. This way, after each iteration, longest will store the longest word found so far in the file.
    • After both loops end, it closes the file using the close method . This releases any resources used by the file object and prevents any errors or data loss.
    • It prints the longest word using the print function. This displays the longest word on the screen.

The final code is:

Function in Python (with comments) that finds and displays the longest word in a text file - Teachoo.png

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.