Lesson 73 +35 XP

Project 5: Word Counter

Project 5: Word Counter

Count how many times each word appears in a sentence using a dictionary.

The goal

Read a sentence, split it into words, and print each word with its count, most common first.

What you practice

  • Dictionaries
  • split()
  • Loops
  • sorted() with a key

Starter code

sentence = input("Type a sentence: ")
words = sentence.lower().split()
print(words)

Step-by-step

  1. Build a dict: counts = {}.
  2. Loop over words; add 1 to counts[word], starting at 0 if new.
  3. Print each word and count.
  4. Sort the results: sorted(counts, key=counts.get, reverse=True).
  5. Handle an empty input gracefully.

Checklist

  • [ ] The sentence is split into words
  • [ ] Every word is counted
  • [ ] Lowercase normalizes the text
  • [ ] Results sort by count
  • [ ] Empty input doesn't crash

TL;DR

  • split() breaks text into words.
  • A dict maps each word to its count.
  • counts[word] = counts.get(word, 0) + 1 counts cleanly.