Python doesn't auto-convert between incompatible types in most operations:
# 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 ✅# 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)# 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!)# 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!This is CRITICAL — almost everything is True in 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!)# 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 defaultCreate 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'.