Module lessons (4/4)
Type conversions
int(), float(), str(), bool(): explicit casting, input parsing, and truthiness rules.
What you'll learn in this lesson
- Explicitly convert incompatible types to
int(),float(),str(),bool(),list(),set(). - Handle parsing traps:
int("42.5")(which fails) vsint(float("42.5"))and base conversion (int("ff", 16)). - Apply the rules of truthiness (
bool(x)) recognizing why"0"and[0]areTruewhile""and0areFalse.
Overview
Since Python is strongly typed, it never performs automatic hidden conversions between strings and numbers: adding "10" + 5 fails right away. To transform data from CSV, form or JSON files you must explicitly invoke the target type constructor (int, float, str, bool, etc.).
Every type name in Python is also a constructor function: int("42") parses the text and allocates a int(42). With bool(x) you instead query whether an object is "empty/zero" (False) or contains useful data (True): be careful though, because non-empty strings like "False" or "0" are always True!
Sections covered in this lesson
- 1The mental model: explicit constructors & truthiness contract
- 2Safe numeric conversions (
int,float, different bases) - 3Truthiness and defensive parsing with
try/except - 4Quick check
- 5Test yourself
Unlock "Type conversions" and the full Python Course curriculum
int(), float(), str(), bool(): explicit casting, input parsing, and truthiness rules.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.