Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! π
Type Conversion & Casting
Type conversion (casting) lets you convert data from one type to another. This is essential when working with user input (which is always a string) or combining different data types.
Type Conversion Functions
- int() - Convert to integer: int('42') = 42, int(3.9) = 3
- float() - Convert to float: float('3.14') = 3.14, float(42) = 42.0
- str() - Convert to string: str(42) = '42', str(True) = 'True'
- bool() - Convert to boolean: bool(0) = False, bool('hello') = True
- input() always returns a string - must convert for math
- Falsy values: 0, 0.0, '', [], {}, None, False β bool() = False
- Everything else is Truthy β bool() = True
Type Conversion Examples
# String to Number
age_str = "25"
age_num = int(age_str)
print(age_num + 5) # 30 (math works!)
# Float conversion
price = float("9.99")
print(price * 2) # 19.98
# Number to String
score = 100
message = "Your score is " + str(score)
print(message)
# Boolean conversion
print(bool(0)) # False
print(bool("")) # False
print(bool(None)) # False
print(bool(42)) # True
print(bool("hello")) # True
print(bool([1, 2])) # True
# User input (always string!)
# name = input("Enter name: ")
# age = int(input("Enter age: "))
# print(f"{name} is {age} years old")Tip
Tip
Always wrap int(input()) in try/except to handle invalid input gracefully. Users will type letters when you expect numbers - your program should handle that without crashing.
input() always returns a string - convert with int() or float() before using in math
Common Mistake
Warning
int() truncates decimals, it does NOT round. int(3.9) = 3, not 4. Use round() for rounding. Also int('hello') raises ValueError - always validate before converting.
Practice Task
Note
Type conversion practice: (1) Convert '42' to int and add 8. (2) Convert 3.14 to int and observe truncation. (3) Test bool() on various values: 0, 1, '', 'hello', [], [1]. (4) Convert True to int.
Quick Quiz
Key Takeaways
- Type conversion (casting) lets you convert data from one type to another.
- int() - Convert to integer: int('42') = 42, int(3.9) = 3
- float() - Convert to float: float('3.14') = 3.14, float(42) = 42.0
- str() - Convert to string: str(42) = '42', str(True) = 'True'