Skip to main content
Albero Academy

Type Conversion

Convert between strings, ints and floats safely, and understand implicit vs explicit conversion.

Fundamentals9 min

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

casting with type constructors
int("42") # 42 str → int
float("3.14") # 3.14 str → float
str(100) # "100" int → str
int(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:

automatic widening
3 + 4.0 # 7.0 (int promoted to float)
True + 1 # 2 (bool acts as 1)

Key takeaways

  1. 01Cast explicitly with int(), float(), str(), bool(), list()…
  2. 02int() on a float truncates toward zero — use round() to round.
  3. 03Python implicitly widens int→float in mixed arithmetic.
  4. 04Converting an invalid string raises ValueError — handle it.

Finished this chapter?

Mark it complete to track your progress through Python.