Quick Overview
An empty string is falsy, so `if not s:` covers it without calling `len()`. That same test also catches `None`, which is usually what you want and occasionally the bug.
Create a function is_empty(s) that returns True if a string is empty and False otherwise.
Validating empty text input prevents processing null values when handling form submissions or user comments.
In Python, an empty string "" is falsy. You can check not s or check if len(s) == 0:
def is_empty(s):
return len(s) == 0
# Pythonic Truthiness Alternative
def is_empty_pythonic(s):
return not s
# Testing our function
print(is_empty("")) # Output: True
print(is_empty(" ")) # Output: False (contains space character!)
print(is_empty("a")) # Output: False
"" (Length 0) evaluates to False in boolean context." " (Space character, length 1) evaluates to True. To check if a string is only whitespace, use not s.strip()." " is NOT an empty string! If you want whitespace-only strings to count as empty, call not s.strip().Use not s for Pythonic empty checks. Next, let's compare string lengths!
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.