Quick Overview
`split()` with no argument collapses runs of whitespace and ignores leading and trailing spaces. `split(" ")` does neither, so a double space yields an empty string in the result.
Create a function count_words(txt) that takes a string of text and returns the total word count.
Text analysis, document search indexing, and social media post validation rely on calculating word counts.
Use the string .split() method to split text by spaces into a list of words, then measure length with len():
def count_words(txt):
words = txt.split()
return len(words)
# Testing our function
print(count_words("Just an example here")) # Output: 4
print(count_words("Is this easy?")) # Output: 3
print(count_words("Hello World")) # Output: 2
Calling .split() without arguments automatically handles multiple consecutive spaces, tabs, and newlines cleanly without creating empty string items.
txt.split(" "): Calling txt.split(" ") fails when multiple spaces exist between words! Always call txt.split() without arguments for general word tokenization.Use txt.split() and len() for word counts. Next, let's find the minimum and maximum numbers in a list!
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.