Learning

Type Conversion & Casting

Type Conversion & Casting

Why Type Conversion?

Python doesn't auto-convert between incompatible types in most operations:

python
# This WORKS (numeric promotion) result = 5 + 2.5 # int + float → float (7.5) # This FAILS (incompatible types) # result = '5' + 2 # TypeError! Can't add str and int # Solution: explicit conversion result = int('5') + 2 # 7 ✅

int() Conversion

python
# From float (truncates, does NOT round) print(int(3.9)) # 3 (not 4!) print(int(-2.7)) # -2 # From string (must be valid integer format) print(int('42')) # 42 print(int(' 42 ')) # 42 (whitespace allowed) # print(int('3.14')) # ValueError! # print(int('abc')) # ValueError! # From boolean print(int(True)) # 1 print(int(False)) # 0 # From other bases print(int('1010', 2)) # 10 (binary) print(int('FF', 16)) # 255 (hexadecimal) print(int('17', 8)) # 15 (octal)

str() Conversion

python
# From any object print(str(42)) # '42' print(str(3.14)) # '3.14' print(str(True)) # 'True' (not '1'!) print(str(None)) # 'None' print(str([1,2,3])) # '[1, 2, 3]' # For custom formatting, use f-strings instead x = 3.14159 print(str(x)) # '3.14159' print(f'{x:.2f}') # '3.14' (formatted!)

float() Conversion

python
# From int print(float(10)) # 10.0 # From string print(float('3.14')) # 3.14 print(float(' -2.5 ')) # -2.5 (whitespace & sign allowed) print(float('inf')) # inf print(float('nan')) # nan # Special strings print(float('1e3')) # 1000.0 # From boolean print(float(True)) # 1.0 print(float(False)) # 0.0 # Edge cases # print(float('3.14.15')) # ValueError! # print(float('abc')) # ValueError!

bool() Conversion — Truthiness

This is CRITICAL — almost everything is True in Python:

python
# Falsy values (only these!) print(bool(False)) # False print(bool(None)) # False print(bool(0)) # False print(bool(0.0)) # False print(bool('')) # False (empty string) print(bool([])) # False (empty list) print(bool(())) # False (empty tuple) print(bool({})) # False (empty dict) print(bool(set())) # False (empty set) print(bool(range(0)))# False (empty range) # EVERYTHING else is True! print(bool(1)) # True print(bool(-1)) # True (any non-zero!) print(bool(' ')) # True (space is non-empty!) print(bool([0])) # True (non-empty list!) print(bool('False')) # True (it's a non-empty string!)

Practical Patterns

python
# Safe user input conversion age = int(input('Enter age: ')) # May crash! # Safer version try: age = int(input('Enter age: ')) except ValueError: print('Invalid number!') age = 0 # Chained conversion result = float(int('42')) # int → float: 42.0 # Conditional conversion def to_int(value, default=0): try: return int(value) except (ValueError, TypeError): return default
Key Rules
  • •int() truncates floats (int(3.9) = 3) — it does NOT round, use round() for rounding
  • •int() can parse strings with whitespace but NOT strings with decimals ('3.14' fails)
  • •int('1010', 2) converts from binary — second arg is the base (2, 8, 10, 16)
  • •bool('False') is True — it's a non-empty string! Only empty string '' is False
  • •bool([0]) is True — non-empty container! Only [] is False regardless of contents
  • •Always wrap input conversion in try/except — users will enter garbage
Your Task

Create a function `safe_convert(value, target_type)` that safely converts a value to 'int', 'float', or 'str'. Return None if conversion fails. Test it with: safe_convert('42', 'int'), safe_convert('abc', 'int'), safe_convert('3.14', 'float'), safe_convert('[1,2,3]', 'str'). Also create a truthiness checker that labels values as 'Truthy' or 'Falsy' for: 0, '', 'hello', [], [0], None, False, 'False'.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define safe_convert function
Should use try/except for error handling
Should test with 'abc' string for int conversion
Should use bool() for truthiness check
Should test 'False' string for truthiness
Should print 'Truthy' or 'Falsy' labels