logo
19

Type Conversion

⏱️ 20 min

Type Conversion: Match Your Types or Watch Things Break

What You Might Be Wondering

"It looks like a number. Why is the program throwing an error?"

Because "123" looks like a number but it's still a string. You have to convert it before you can do math with it.

One-Line Definition

Type conversion changes data from one type to another so it's compatible with the operation you need.

Real-Life Analogy

A bilingual team needs to agree on one language before they can collaborate efficiently. Same with data — unify the types before processing.

Minimal Working Example

x = 10      # int
y = 2.5     # float
z = x + y   # float
print(z, type(z))

Explicit Conversion

print(int("123"))
print(float("3.14"))
print(str(99))
print(bool(0))      # False
print(bool("hi"))  # True

Container Conversion

nums = [1, 2, 2, 3]
print(set(nums))
print(tuple(nums))
print(list(("a", "b")))

Fixing the Classic TypeError

# Error: TypeError
# total = "100" + 20

total = int("100") + 20
print(total)  # 120

Quick Quiz (5 min)

  1. Convert "2026" to an integer and add 10.
  2. Convert a list of float strings into a list of actual floats.
  3. Use set to deduplicate a list.

Quiz Rubric & Grading Criteria

  • Direction: write runnable code that covers the core requirements and edge cases from the prompt.
  • Criterion 1 (Correctness): main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.

Take-Home Task

Write an "order amount processor" function:

  • Input: a list of amount strings
  • Convert to numbers and sum them up
  • Output: total and average

Acceptance Criteria

You can independently:

  • Tell the difference between implicit and explicit conversion
  • Use int/float/str/bool fluently
  • Locate and fix basic type mismatch errors

Common Errors & Debugging Steps (Beginner Edition)

  • Error message looks like gibberish: read the last line for the error type (TypeError, NameError, etc.), then trace back to the offending line.
  • Not sure what a variable holds: drop a temporary print(variable, type(variable)) to check.
  • Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.

Common Misconceptions

  • Misconception: int("3.14") works directly.

  • Reality: nope. You need float("3.14") first, then int(...).

  • Misconception: bool("False") returns False.

  • Reality: any non-empty string is True. Even the string "False".