Type Casting
Converting between types
| Function | Converts to | Example |
|---|---|---|
int() | whole number | int("42") → 42 |
float() | decimal | float("3.14") → 3.14 |
str() | text | str(99) → "99" |
bool() | True/False | bool(0) → False |
Things that surprise beginners
int(3.9)→3: it cuts off the decimal, it does not round.round(2.5)→2andround(3.5)→4: Python rounds halves to the nearest even number.int("3.5")raisesValueError. Useint(float("3.5")).bool("False")isTrue! Any non-empty string is truthy.
Truthy and falsy
These count as False: 0, 0.0, "", [], {}, set(), None. Everything else is True.
Implicit conversion
Python mixes int and float automatically (1 + 2.0 → 3.0), but never str and numbers: "Age: " + 21 is a TypeError. Use str(21) or an f-string.
Safe conversion
Wrap risky conversions in try/except ValueError (Module 6).
▶️ Runs in the app.
Example
print(int("123") + 1) # 124
print(float("3.14") * 2) # 6.28
print(str(99) + " points") # 99 points
print(int(3.9)) # 3 (truncates)
print(round(2.5), round(3.5)) # 2 4 (round half to even)
print(bool(""), bool("False")) # False True
# Converting user-style input safely
text = "12a"
try:
number = int(text)
except ValueError:
print(f"'{text}' is not a whole number")