8.15 Common Mistakes
The most common type conversion bugs in Python — parsing a decimal string with int() directly, silent data loss from float to int, and the bool('False') gotcha.
Invalid Conversions
Trying to int() a decimal-looking string directly fails, because int() expects a string that’s already a whole number — go through float() first if the string might have a decimal point.
>>> int("3.14")
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: '3.14'
>>> int(float("3.14")) # correct two-step approach
3
Data Loss
Converting float to int silently discards the fractional part (see 8.4 Numeric Type Conversion) — easy to miss if not paying attention, since no error or warning is raised.
>>> price = 19.99
>>> int(price) # silently loses the cents -- no error at all
19
Incorrect Boolean Conversion
What Goes Wrong?
Assuming bool("False") or bool("0") returns False, because the text looks like a negative value. In reality, any non-empty string is truthy, regardless of its content.
>>> bool("False") # non-empty string -- ALWAYS True
True
>>> bool("0") # also True -- a very common gotcha
True
# Correct way to parse a boolean-looking string:
>>> value = "False"
>>> value.lower() == "true"
False
Quick Interview Answer
“Three conversion bugs come up constantly: calling
int()directly on a decimal-looking string, which raisesValueErrorbecauseint()only accepts strings that are already whole numbers — the fix isint(float(x)); silently losing precision convertingfloattoint, since truncation raises no warning at all; and assumingbool()parses boolean-looking text semantically —bool(\"False\")andbool(\"0\")are bothTrue, because any non-empty string is truthy regardless of content. Parsing an actual boolean-looking string correctly means comparing its lowercased text against\"true\"explicitly, not callingbool()on it.”
Common Mistakes
- Calling
bool(some_string)to parse a config value that’s textually"true"/"false"— it always returnsTruefor any non-empty string; compare the lowercased text instead. - Not noticing
int(19.99)silently drops the cents — worth an explicitround()first if the intent is rounding rather than truncation. - Skipping the
float()intermediate step when parsing a decimal string withint(), hitting an avoidableValueError.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form