1 The Problem
We want a tool that takes some text — typed in or read from a file — and reports how many words, characters, and lines it has. It teaches the core string operations for breaking text into pieces and measuring them.
Where this shows up: word-count limits on forms and essays, reading-time estimates, search indexing, text analysis, validating input length. Measuring and slicing text is one of the most common jobs in software.
2 How to Think About It
Think about what “counting words” really means, before any code:
The plan — in plain English
1. Get the text. → 2. Characters = how long the text is (len). → 3. Words = split the text on spaces and count the pieces. → 4. Lines = split on line-breaks and count those. → 5. Show the three numbers.
3 The Build — explained part by part
Here is the complete word counter. Each line is explained below.
Pythonwordcount.py
# Count words, characters, and lines in some text.
print("Paste your text, then press Enter twice to finish:")
lines = []
while True:
line = input()
if line == "": # an empty line means "done"
break
lines.append(line)
text = "\n".join(lines)
char_count = len(text)
word_count = len(text.split()) # split() breaks on any whitespace
line_count = len(lines)
print(f"Characters: {char_count}")
print(f"Words: {word_count}")
print(f"Lines: {line_count}")
What each part does — in plain words
The while loop — collects lines of text until the user enters a blank line. Each typed line is added to the lines list.text = "\n".join(lines) — glue the lines back into one block of text, with line-breaks between them.
len(text) — the number of characters is simply the length of the text.
text.split() — this is the key move:
split() with no argument breaks the text wherever there is a space or newline, giving a list of words. len() of that list is the word count.len(lines) — we already have the lines in a list, so counting them is just its length.
Common mistakes — and how to avoid them
✗ Using
text.split(" ") with a space argument — then double spaces create empty “words”.✓ Use
split() with no argument; it handles any whitespace and ignores repeats.✗ Counting characters with a loop — unnecessary;
len(text) already does it.✓ Reach for
len() — it is built for this.✗ Forgetting that a blank line ends input — the loop never stops.
✓ Check
if line == "": break inside the loop.4 Test & Prove Each Part
We test the counting logic on text where we already know the answer.
"hello world" has 2 words
An empty string has 0 words
Counting characters matches the text length
Pythontest_wordcount.py
def count_words(text):
return len(text.split())
def count_chars(text):
return len(text)
def test_two_words():
"""'hello world' has 2 words."""
assert count_words("hello world") == 2
def test_empty():
"""Empty text has 0 words."""
assert count_words("") == 0
def test_extra_spaces():
"""Extra spaces do not create fake words."""
assert count_words(" hello world ") == 2
def test_char_count():
"""Character count matches the length."""
assert count_chars("abc") == 3
Run with pytest -v. The extra-spaces test is important: split() cleverly ignores repeated spaces, so “hello world” is still 2 words, not more.
5 The Interface
INPUTtexttyped lines, blank line to finish
What it expects
The quick brown fox
jumps over the dog
[blank line]OUTPUTcountscharacters, words, lines
What it returns
Characters: 37
Words: 8
Lines: 26 Run It & Automate It
Run it locally
python3 wordcount.pyType or paste text, then press Enter on a blank line to see the counts.
Jenkins runs the tests automatically — each line explained below.
What you should see when it works
Terminala real run
Paste your text, then press Enter twice to finish:
The quick brown fox
jumps over the lazy dog
Characters: 39
Words: 8
Lines: 2If it breaks — how to fix it
🚨 Word count is higher than expected.
You probably used
split(" "). Switch to plain split().🚨 The program never stops asking for input.
Your blank-line check is missing or wrong. It must
break on an empty line.GroovyJenkinsfile
// Jenkinsfile — automated tests on every change.
pipeline {
agent any
stages {
stage('Get the code') { steps { checkout scm } } // download the code
stage('Install') { steps { sh 'python3 -m venv venv && . venv/bin/activate && pip install pytest' } } // test tool
stage('Test') { steps { sh '. venv/bin/activate && pytest -v' } } // run every test
}
post {
success { echo 'All tests passed.' }
failure { echo 'A test failed — look above.' }
}
}
🎯 Try this next — make it yours
- Read from a file. Count a whole document instead of typed text. (Teaches: file reading.)
- Reading time. Estimate minutes to read (words ÷ 200). (Teaches: a calculation.)
- Most common word. Find which word appears most. (Teaches: counting with a dictionary.)
What you learned
You learned the core string operations: len() to measure, split() to break text into words, and join() to glue it back. These three handle most text work you will ever do. Related: String Methods.