Input a sentence, count its words and display the longest word
Expt. No.17
Page No.34
Count words and find the longest
Aim
To write a Python program that counts the words in a sentence and displays the longest word.
Concepts used
Algorithm
- Input a sentence.
- Split it into a list of words with
split(). - The number of words is the length of the list.
- Go through the words; keep the one with the greatest length.
- Display the count and the longest word.
Program
# Count the words in a sentence and find the longest word sentence = input("Enter a sentence: ")words = sentence.split()print("Number of words:", len(words)) longest = ""for w in words: if len(w) > len(longest): longest = wprint("Longest word:", longest, "(", len(longest), "letters )")
A marked line continues the line above it. In your file, write it on the same line.
Output
$ python count_words_longest_word.py
Enter a sentence: Practice makes a programmer perfect
Number of words: 5
Longest word: programmer ( 10 letters )
✓ Printed by running this program, not typed by hand.
Result
The sentence had 5 words, and the longest was "programmer" with 10 letters.
Viva voce: what the examiner may ask
01What does split() return?
A list of the words in the string. With no argument it splits on any run of spaces.
02What does len() give for a list and for a string?
For a list, the number of items; for a string, the number of characters.
03If two words are equally long, which one is displayed?
The first one, because the condition uses > and not >=.
Variations for the lab test
- Display the shortest word too.
- Display each word with its length.
- Display the words that start with a capital letter.
! Common mistake Counting words with
sentence.count(" ") + 1 gives the wrong answer when there are two spaces in a row.