Python Casting
Convert between strings, numbers, and booleans with int(), float(), and str().
Why it matters: Config and model outputs often arrive as strings. Convert them explicitly.
Basics
Casting Functions
Python will not mix strings and numbers for you.
int(x)- whole numberfloat(x)- decimalstr(x)- textbool(x)- True or False
int("12.5") fails. Use int(float("12.5")) instead.
Common mistake: forgetting to convert env strings before math.
Tiny example
Convert a string to a float.
raw = "0.2"
temperature = float(raw)
print(temperature)
print(type(temperature))Basics
Safe Parsing
bool("False") is True because the string is not empty.
Compare against a set like {"1", "true", "yes"} instead.
Never use eval() on outside input.
Tiny example
Parse a bool from text against a known set.
raw = "false"
print(raw.lower() in {"1", "true", "yes"})Basics
Float Precision
Floats are approximate. That is binary floating point.
Do not compare floats with ==. Use math.isclose(a, b).
Common mistake: treating float equality as exact.
Tiny example
0.1 + 0.2 is not exactly 0.3.
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: cast config strings
Turn text settings into numbers.
In AI / ML: Temperature and max tokens often start as env strings.
example.py
Python
raw = "0.7"
temperature = float(raw)
max_tokens = int("512")
print(temperature)
print(max_tokens)AI / ML example 2
AI / ML: bool from text
Do not use bool() on the string False.
In AI / ML: Flags like STREAM often arrive as text, not real booleans.
example.py
Python
raw = "False"
print(bool(raw))
print(raw.lower() in {"1", "true", "yes"})Takeaways
- 1Convert strings and numbers explicitly.
- 2int() truncates. Use float() first for decimals.
- 3bool("False") is True. Parse booleans carefully.