- Read the question carefully (twice).
- Break the task into the smallest steps.
- Sketch or write pseudocode before coding.
- Start small — test as you go.
- Check your solution with different cases.
Overview
Write a function that takes a sentence as input and returns how many words it contains.
- Words are separated by spaces.
- Ignore extra spaces at the beginning, end, or between words.
Learning objectives
You should be able to:
- Use string methods to split text.
- Handle multiple spaces.
- Write a simple function that returns a number.
Success criteria
word_count(sentence)returns an integer.- Works with normal sentences.
- Handles multiple spaces cleanly.
- Returns
0if the sentence is empty or only spaces.
Skeleton (Python) — word_counter.py
def word_count(sentence: str) -> int:
"""Return the number of words in the sentence.
Words are separated by spaces. Ignore extra spaces.
"""
if not isinstance(sentence, str):
raise ValueError("Input must be a string")
# Remove leading/trailing whitespace
sentence = sentence.strip()
if not sentence:
return 0
# Split by spaces and filter out empties
words = [w for w in sentence.split(" ") if w]
return len(words)
Manual examples
>>> from word_counter import word_count
>>> word_count("Hello world")
2
>>> word_count(" This has extra spaces ")
4
>>> word_count("")
0
Tests — test_word_counter.py
from word_counter import word_count
import pytest
def test_basic():
assert word_count("Hello world") == 2
def test_extra_spaces():
assert word_count(" Too many spaces here ") == 4
def test_empty_string():
assert word_count("") == 0
def test_only_spaces():
assert word_count(" ") == 0
def test_single_word():
assert word_count("Python") == 1
Stretch goals (optional)
- Handle punctuation better:
"Hello, world!"→ 2 words. - Count unique words instead of total words.
- Return both the number of words and the list of words.