Python Basics — Type Conversion
Type Conversion
Type conversion (also called type casting) is the process of converting a value from one data type to another. Python supports two kinds: implicit (automatic) and explicit (manual).
Implicit Type Conversion (Coercion)
Python automatically converts one type to another when it makes sense — without you asking:
# int + float → float (Python "promotes" the int to float)
result = 5 + 3.0
print(result) # 8.0
print(type(result)) # <class 'float'>
# int + bool → int (True = 1, False = 0)
result = 10 + True
print(result) # 11
print(type(result)) # <class 'int'>
Implicit Conversion Hierarchy
When mixing types in an operation, Python promotes to the “wider” type:
bool → int → float → complex
# bool + int → int
print(True + 5) # 6
# int + float → float
print(3 + 2.5) # 5.5
# float + complex → complex
print(1.5 + 2j) # (1.5+2j)
Python does NOT implicitly convert between strings and numbers:
# ❌ This causes a TypeError
# print("Age: " + 25) # TypeError: can only concatenate str to str
Explicit Type Conversion (Casting)
Use built-in functions to manually convert between types:
int() — Convert to Integer
print(int(3.7)) # 3 (truncates decimal, does NOT round)
print(int(3.2)) # 3
print(int(-3.7)) # -3 (truncates toward zero)
print(int("42")) # 42 (string to int)
print(int(True)) # 1
print(int(False)) # 0
print(int("0b1010", 2)) # 10 (binary string to int)
print(int("0xFF", 16)) # 255 (hex string to int)
Common error:
# ❌ Cannot convert a non-numeric string
# int("hello") # ValueError: invalid literal for int()
# ❌ Cannot directly convert a float string
# int("3.14") # ValueError — convert to float first
print(int(float("3.14"))) # 3 ✅
float() — Convert to Float
print(float(42)) # 42.0
print(float("3.14")) # 3.14
print(float("42")) # 42.0
print(float(True)) # 1.0
print(float("inf")) # inf (positive infinity)
print(float("-inf")) # -inf (negative infinity)
str() — Convert to String
print(str(42)) # "42"
print(str(3.14)) # "3.14"
print(str(True)) # "True"
print(str(None)) # "None"
print(str([1, 2, 3])) # "[1, 2, 3]"
bool() — Convert to Boolean
# Numbers
print(bool(0)) # False
print(bool(1)) # True
print(bool(-5)) # True (any non-zero number)
print(bool(0.0)) # False
# Strings
print(bool("")) # False (empty string)
print(bool("hello")) # True (non-empty string)
print(bool("False")) # True! (non-empty string — the content doesn't matter)
# Collections
print(bool([])) # False (empty list)
print(bool([0])) # True (non-empty list, even if element is falsy)
# None
print(bool(None)) # False
Conversion Functions Summary
| Function | Converts To | Examples |
|---|---|---|
int(x) |
Integer | int(3.7) → 3, int("42") → 42 |
float(x) |
Float | float(42) → 42.0, float("3.14") → 3.14 |
str(x) |
String | str(42) → "42", str(True) → "True" |
bool(x) |
Boolean | bool(0) → False, bool("hi") → True |
list(x) |
List | list("abc") → ["a","b","c"] |
tuple(x) |
Tuple | tuple([1,2]) → (1, 2) |
set(x) |
Set | set([1,1,2]) → {1, 2} |
Common Conversion Errors
| Conversion | Input | Error | Fix |
|---|---|---|---|
int("hello") |
Non-numeric string | ValueError |
Validate input first |
int("3.14") |
Float string | ValueError |
Use int(float("3.14")) |
int([1, 2]) |
List | TypeError |
Use int(my_list[0]) |
float("abc") |
Non-numeric string | ValueError |
Validate input first |
Handling Conversion Errors
user_input = "not a number"
try:
number = int(user_input)
print(f"You entered: {number}")
except ValueError:
print("That's not a valid number!")
Output:
That's not a valid number!
Type Checking with isinstance()
Use isinstance() to check if a value is of a certain type:
x = 42
print(isinstance(x, int)) # True
print(isinstance(x, float)) # False
print(isinstance(x, (int, float))) # True (check multiple types)
name = "Alice"
print(isinstance(name, str)) # True
isinstance() vs type():
# type() checks the exact type
print(type(True) == int) # False (type is bool, not int)
# isinstance() respects inheritance (bool is a subclass of int)
print(isinstance(True, int)) # True
Best practice: Use isinstance() over type() comparisons because it handles inheritance correctly.
Practical Examples
Example 1: User Input Calculation
# input() always returns a string — you must convert it
price = float(input("Enter the price: "))
quantity = int(input("Enter the quantity: "))
total = price * quantity
print(f"Total: ${total:.2f}")
Example 2: Building a Report String
name = "Alice"
score = 95
passed = True
# Convert everything to strings for concatenation
report = name + " scored " + str(score) + " — Passed: " + str(passed)
print(report) # Alice scored 95 — Passed: True
# Better approach: use f-strings (no manual conversion needed)
report = f"{name} scored {score} — Passed: {passed}"
print(report) # Alice scored 95 — Passed: True
Common Mistakes
| Mistake | Example | Fix |
|---|---|---|
Assuming int() rounds |
int(3.7) → 3 (truncates) |
Use round(3.7) → 4 |
bool("False") is True |
Non-empty string = truthy | Check value, not just bool() |
| Forgetting to cast input | input() returns string |
Use int(input(...)) |
| Chaining impossible casts | int("3.14") fails |
int(float("3.14")) |
Summary
- Implicit conversion happens automatically (int → float, bool → int)
- Explicit conversion uses functions:
int(),float(),str(),bool() int()truncates (doesn’t round) — useround()if you want roundinginput()always returns a string — convert withint()orfloat()- Use isinstance() to check types (better than
type()) - Handle conversion errors with try/except for user-facing code
- f-strings avoid the need for manual
str()conversion in most cases
Next up: Practice Exercises →