Data often arrives as the wrong type — a number as text from input() or a file. Type conversion (casting) turns one type into another.
Explicit conversion
int("42") # 42 str → intfloat("3.14") # 3.14 str → floatstr(100) # "100" int → strint(3.9) # 3 float → int (truncates, doesn't round!)bool(0) # False (0, "", [], None are falsy)list("abc") # ['a', 'b', 'c']
Implicit conversion
Python quietly widens types in mixed arithmetic — an int plus a float becomes a float:
3 + 4.0 # 7.0 (int promoted to float)True + 1 # 2 (bool acts as 1)
Key takeaways
- 01Cast explicitly with int(), float(), str(), bool(), list()…
- 02int() on a float truncates toward zero — use round() to round.
- 03Python implicitly widens int→float in mixed arithmetic.
- 04Converting an invalid string raises ValueError — handle it.
