Beginner16 min

Type casting and conversion

Convert between strings, integers, floats, booleans, and collections — and do it safely when the input comes from outside.

Why this matters in AI / ML / GenAI

Config files, environment variables, CSV columns, and JSON from an LLM all arrive as strings. The classic production bug is a temperature of "0.2" (string) silently behaving differently from 0.2 (float). Explicit, guarded conversion prevents it.

The conversion functions

Python does not convert types implicitly between strings and numbers — "3" + 4 is a TypeError, not 7. You convert explicitly:

  • int(x) — to integer. From a float it truncates toward zero, it does not round: int(3.9) is 3.
  • float(x) — to float.
  • str(x) — to text. Works on anything.
  • bool(x) — to True/False using truthiness rules.
  • list(x), tuple(x), set(x), dict(pairs) — between collections.

int("12.5") raises ValueError — int cannot parse a decimal string. Go through float first: int(float("12.5")).

For real rounding use round(x), and note Python uses banker's rounding: round(0.5) is 0, round(1.5) is 2. When money or reporting is involved, use decimal.Decimal.

Safe parsing

Any conversion of outside data can fail. Wrap it:

try:
    value = float(raw)
except (TypeError, ValueError):
    value = default

TypeError covers None; ValueError covers "abc". Catch both.

The most dangerous case is bool() on strings. Every non-empty string is True, so bool("False") is True and bool("0") is True. Environment variables are strings, so DEBUG=False read naively enables debug mode. Compare against a set of known values instead.

Never use eval() to parse input. It executes arbitrary code. Use json.loads or ast.literal_eval.

Floats are approximate

0.1 + 0.2 is 0.30000000000000004. This is IEEE 754 binary floating point, not a Python quirk — every language does it.

Consequences:

  • Never test floats with ==. Use math.isclose(a, b).
  • Never store money as a float. Use Decimal or integer paise/cents.
  • Accumulated error matters in long-running numeric loops; NumPy's float32 has even less precision than Python's float (which is float64).

Copy-paste examples

Copy into your own editor, or load one into the compiler below and press Run.

Basic conversions

Note that int() truncates instead of rounding.

print(int("42"), type(int("42")).__name__)
print(float("3.14"))
print(str(99) + " problems")
print(int(3.99), "<- truncated, not rounded")
print(round(3.99), "<- rounded")
print(int(float("12.5")), "<- two-step parse")

print(list("abc"))
print(tuple([1, 2, 3]))
print(set([1, 1, 2, 2, 3]))
print(dict([("a", 1), ("b", 2)]))

The bool() trap with environment variables

Run this — bool("False") being True is a real production bug.

print('bool("False") =', bool("False"))
print('bool("0")     =', bool("0"))
print('bool("")      =', bool(""))
print("bool(0)       =", bool(0))
print("bool([])      =", bool([]))

TRUTHY = {"1", "true", "yes", "on"}

def parse_bool(raw, default=False):
    if raw is None:
        return default
    return str(raw).strip().lower() in TRUTHY

for raw in ["true", "False", "1", "0", "yes", None]:
    print(f"parse_bool({raw!r}) -> {parse_bool(raw)}")

Safe numeric parsing with defaults

This is the shape of every config loader you will write.

def to_float(raw, default=0.0, low=None, high=None):
    try:
        value = float(raw)
    except (TypeError, ValueError):
        return default
    if low is not None and value < low:
        return low
    if high is not None and value > high:
        return high
    return value

for raw in ["0.7", "abc", None, "5.0", "-1"]:
    print(f"{raw!r:8} -> {to_float(raw, default=0.2, low=0.0, high=2.0)}")

Float precision

Use math.isclose for comparisons, never ==.

import math

print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))

from decimal import Decimal
print(Decimal("0.1") + Decimal("0.2"))
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))

print(f"formatted: {0.1 + 0.2:.2f}")

Build a config parser

Try it — in-browser Python

Add a bad value like "hot" for temperature and confirm the default is used.

Output

Python runs in your browser. First run downloads the runtime.

Press Run (or Ctrl+Enter) to execute.

CPython in WebAssembly. Stdlib works. NumPy, pandas, scikit-learn and Matplotlib load on demand, and charts render below. No input(), no GPU, no network installs.

Takeaways

  • Python never converts between strings and numbers implicitly — do it explicitly.
  • int() truncates; round() rounds; int("1.5") raises, so parse through float().
  • bool("False") is True — parse booleans against a known set of strings.