Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What is Type Casting?


What you need to know

Explicit casting

Python
print(int("42"), float("3.14"), str(99))   # 42 3.14 99print(int(3.99), int(-3.99))               # 3 -3   -> truncates towards 0print(list("abc"))                         # ['a', 'b', 'c']print(tuple([1, 2]), set([1, 1, 2]))       # (1, 2) {1, 2}print(int(" 42\n"))                        # 42     -> surrounding spaces are finetry:    int("3.5")except ValueError as e:    print(e)          # invalid literal for int() with base 10: '3.5'print(int(float("3.5")))                   # 3      -> two steps

int() 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 valuesEverything 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:

Python
def to_float(value, default=0.0):    try:        return float(value)    except (TypeError, ValueError):        return defaultdef to_bool(value):    if isinstance(value, bool):        return value    return str(value).strip().lower() in {"true", "yes", "1"}reply = {"confidence": "0.87", "is_fraud": "false", "amount": "1,299.00"}print(to_float(reply["confidence"]))                  # 0.87print(bool(reply["is_fraud"]), to_bool(reply["is_fraud"]))   # True Falseprint(to_float(reply["amount"].replace(",", "")))     # 1299.0print(to_float(None))                                 # 0.0

The 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) and round(3.9)?" — int truncates to 3; round returns 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?" — ValueError for a bad value like int("abc"), and TypeError for an unsupported type like int(None).