ByteBoard Notes Notes

Input a sentence, count its words and display the longest word

Computer Science XI · Experiment 17 of 27 · Python

11-CSPython programs
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

  1. Input a sentence.
  2. Split it into a list of words with split().
  3. The number of words is the length of the list.
  4. Go through the words; keep the one with the greatest length.
  5. 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

  1. Display the shortest word too.
  2. Display each word with its length.
  3. 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.
Back to the 11-CS index