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.
1. Read
Understand the idea in plain English first.
2. Run
Load any example into the compiler and press Run.
3. Change
Edit one value, rerun, and learn from the output.
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)is3.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
==. Usemath.isclose(a, b). - Never store money as a float. Use
Decimalor integer paise/cents. - Accumulated error matters in long-running numeric loops; NumPy's
float32has even less precision than Python'sfloat(which isfloat64).
Hands-on practice
Compiler on the left. Examples on the right.
On desktop, keep the compiler beside the examples. On mobile, the same blocks stack cleanly. Pick an example, try it in the compiler, then change one small thing.
Build a config parser
Live Python compiler
Try it — in-browser Python
Add a bad value like "hot" for temperature and confirm the default is used.
Code editor
Output
Python runs in your browser. First run downloads the runtime.
Press Run (or Ctrl+Enter) to execute.
Runs CPython in your browser. NumPy, pandas, scikit-learn and Matplotlib load on demand. Charts appear below the output. No input(), no GPU, no network installs.
Clear code examples
Every example is copy-ready. Use Try in compiler when you want to experiment without scrolling around.
Example
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)]))Example
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)}")Example
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)}")Example
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}")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.