Python · Module 1 · Lesson 41 min read

Type Casting

Converting between types

FunctionConverts toExample
int()whole numberint("42") → 42
float()decimalfloat("3.14") → 3.14
str()textstr(99) → "99"
bool()True/Falsebool(0) → False

Things that surprise beginners

  • int(3.9) → 3: it cuts off the decimal, it does not round.
  • round(2.5) → 2 and round(3.5) → 4: Python rounds halves to the nearest even number.
  • int("3.5") raises ValueError. Use int(float("3.5")).
  • bool("False") is True! 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

Python
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")