๐Ÿ“ฆ Python Fundamentals
Module 2 ยท Topic 3

Type Conversion & Type Checking

Convert between data types using built-in functions and understand when Python converts types implicitly vs when you must do it explicitly.

Theory

Type Conversion (Casting) in Python:

Implicit Conversion (Coercion):
Python automatically converts types in some arithmetic operations:

  • int + float โ†’ float: 5 + 2.0 = 7.0
  • int + complex โ†’ complex: 5 + 3j = (5+3j)
  • bool + int โ†’ int: True + 5 = 6

Explicit Conversion (Casting):
Use built-in constructor functions:

| Function | Purpose | Example |
|----------|---------|--------|
| int() | Convert to integer | int("42") โ†’ 42, int(3.9) โ†’ 3 |
| float() | Convert to float | float("3.14") โ†’ 3.14, float(5) โ†’ 5.0 |
| str() | Convert to string | str(42) โ†’ "42", str([1,2]) โ†’ "[1, 2]" |
| bool() | Convert to boolean | bool(0) โ†’ False, bool("") โ†’ False |
| list() | Convert to list | list("abc") โ†’ ["a","b","c"] |
| tuple() | Convert to tuple | tuple([1,2]) โ†’ (1, 2) |
| set() | Convert to set | set([1,1,2]) โ†’ {1, 2} |
| dict() | Convert to dict | dict([(a,1),(b,2)]) โ†’ {"a":1,"b":2} |

Truthy & Falsy Values:
These convert to False: 0, 0.0, "", [], (), {}, set(), None, False
Everything else is True.

Syntax
# Explicit conversion
int("42")       # String to int โ†’ 42
float("3.14")   # String to float โ†’ 3.14
str(100)        # Int to string โ†’ "100"
bool(0)         # Int to bool โ†’ False
list("hello")   # String to list โ†’ ["h","e","l","l","o"]