SolveWithPython

Challenge 2: Count Words in a Sentence

You’ll write a function that counts words in a sentence.
This mimics basic text analysis tasks.
Estimated time: 10 minutes | Difficulty: Beginner

Problem

Count how many words appear in a given sentence.

Inputs

  • sentence: str

Output

Return an integer word count.

Examples

Input String

“Python is fun”

Output String

3

Constraints

  • Words are separated by spaces
  • Ignore extra spaces

Requirements

  • Function name: count_words(sentence: str) -> int
  • Parameter: sentence (string)
  • Return type: int

Starter Code

def count_words(sentence: str) -> int:
pass

Edge Cases to Consider

  • Empty string
  • String with only spaces
  • Multiple spaces between words

Python Challenge 2 Solution Count Words In A Sentence
Python Challenge 2 Solution Count Words In A Sentence

Explanation

  • split() without arguments automatically handles multiple spaces
  • Time complexity: O(n)
  • Space complexity: O(n)

Python Challenge 2 Test Count Words In A Sentence

You can use the following tests above to verify your solution locally.

🔗 View reference solution on GitHub
(After you’ve tried the challenge)

Nice work!

You’ve completed this challenge. The best way to improve your Python skills is to keep practicing while the concept is fresh.

👉 Next Challenge → Find the Largest Number in a List

Want more practical Python challenges?
Subscribe to the Solve With Python newsletter and get new problems delivered to your inbox.