Skip to main content
Module 4 · Lesson 4 of 416/36 in the course~14 min
Module lessons (4/4)

Type conversions

Lesson preview5 hands-on exercises readyPython Course · Module 4 — Strings and numbers

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) vs int(float("42.5")) and base conversion (int("ff", 16)).
  • Apply the rules of truthiness (bool(x)) recognizing why "0" and [0] are True while "" and 0 are False.

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

  1. 1The mental model: explicit constructors & truthiness contract
  2. 2Safe numeric conversions (int, float, different bases)
  3. 3Truthiness and defensive parsing with try/except
  4. 4Quick check
  5. 5Test yourself
Pro Lesson · Module 4 — Strings and numbers

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.