Python Exercise: Find the longest word in a paragraph

Longest word in a paragraph

Python Programming Exercise

Instructions

The goal of this Python programming exercise is to write a Python 3 program that finds the longest word in a given paragraph or text. Your program should specifically analyze the following text and return the longest word found within it.

“While the user hasn’t lost the game, we show a randomly generated string of length k for three seconds at a time. Then, we clear the screen by printing a ton of new lines. I’m using a terminal that’s small enough to be cleared with 100 lines. When the user inputs the correct string, we increment k by 1. As long as the user keeps winning, we keep playing. When the user misses a letter, we tell the user their score and end the game.”

This Python programming exercise is aimed at beginners – intermediate students willing to practice core topics such as functions and loops. To work on other subjects, visit Practity’s real life projects.

Guidelines

To complete this assignment, please follow these steps:

1. Define a function called `find_longest_word` that takes a string parameter representing the text to be analyzed.
2. Inside the function, split the text into individual words using whitespace as the delimiter.
3. Initialize a variable called `longest_word` to an empty string.
4. Iterate through each word in the list of words.
5. For each word, compare its length to the length of the current `longest_word`. If the length of the current word is greater than the length of `longest_word`, update `longest_word` to be the current word.
6. After iterating through all the words, return the value of `longest_word`.
7. Outside the function, call the `find_longest_word` function with the provided text as the argument.
8. Print the returned value to display the longest word.
9. Test your program using different texts.

Solution

def find_longest_word(text):
    words = text.split()
    longest_word = ''
    for word in words:
        if len(word) > len(longest_word):
            longest_word = word
    return longest_word

text = "While the user hasn’t lost the game, we show a randomly generated string of length k for three seconds at a time. Then, we clear the screen by printing a ton of new lines. I’m using a terminal that’s small enough to be cleared with 100 lines. When the user inputs the correct string, we increment k by 1. As long as the user keeps winning, we keep playing. When the user misses a letter, we tell the user their score and end the game."

result = find_longest_word(text)
print("The longest word in the text is:", result)

## Output
The longest word in the text is: generated

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for Practice
Register New Account
Shopping cart