Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is Type Casting?
What you need to know
Explicit casting
1print(int("42"), float("3.14"), str(99)) # 42 3.14 992print(int(3.99), int(-3.99)) # 3 -3 -> truncates towards 03print(list("abc")) # ['a', 'b', 'c']4print(tuple([1, 2]), set([1, 1, 2])) # (1, 2) {1, 2}5print(int(" 42\n")) # 42 -> surrounding spaces are fine6try:7 int("3.5")8except ValueError as e:9 print(e) # invalid literal for int() with base 10: '3.5'10print(int(float("3.5"))) # 3 -> two stepsint() accepts whole-number strings only. For a decimal string you go through float() first. Strings with commas like "1,299" also fail, so you strip the comma first.
Implicit conversion
In mixed arithmetic Python widens to the "bigger" numeric type: bool → int → float → complex. So True + 1 is 2, and 1 + 2.0 is 3.0. It never converts between text and numbers for you.
Truthiness: what bool() does
bool(x) does not parse text. It asks "is this empty or zero?"
| Falsy values | Everything else is truthy |
|---|---|
False, None, 0, 0.0, "", [], {}, set() | "False", "0", [0], -1, " " |
So bool("False") is True, because it is a non-empty string.
A real-life example
You ask an LLM to return JSON, but models are not always consistent with types. One reply has "confidence": "0.87" as a string and "is_fraud": "false" as a string. You write small, safe converters:
1def to_float(value, default=0.0):2 try:3 return float(value)4 except (TypeError, ValueError):5 return default67def to_bool(value):8 if isinstance(value, bool):9 return value10 return str(value).strip().lower() in {"true", "yes", "1"}1112reply = {"confidence": "0.87", "is_fraud": "false", "amount": "1,299.00"}13print(to_float(reply["confidence"])) # 0.8714print(bool(reply["is_fraud"]), to_bool(reply["is_fraud"])) # True False15print(to_float(reply["amount"].replace(",", ""))) # 1299.016print(to_float(None)) # 0.0The naive bool(reply["is_fraud"]) would have flagged every transaction as fraud. In real projects you often let Pydantic do this parsing and validation for you, but you still need to know what it is doing underneath.
Follow-up questions to expect
- "What is the difference between
int(3.9)andround(3.9)?" —inttruncates to 3;roundreturns the nearest integer, 4. - "Why is
bool("False")True?" —bool()checks emptiness, and any non-empty string is truthy. - "What error does a failed cast raise?" —
ValueErrorfor a bad value likeint("abc"), andTypeErrorfor an unsupported type likeint(None).