► Overview
Type conversion is changing data from one type to another (like string to integer). This is essential when working with user input or combining different data types.
► Real-World Analogy
Think of type conversion like translating languages:
» You receive information in one language (type)
» You translate it to another language you understand
» The meaning stays the same, just the form changes
» Sometimes translation is needed for communication
► Key Concepts
✓ Type Conversion: Changing one data type to another
✓ int(): Converts to integer
✓ float(): Converts to decimal number
✓ str(): Converts to string
■ Conversion Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# String to integer age_str = "25" age_int = int(age_str) print(age_int + 5) # 30 # String to float price = float("19.99") print(price * 2) # 39.98 # Integer to string count = 100 message = "Count: " + str(count) print(message) # Count: 100 ► Important Points ✓ input() always returns a string - convert it when needed ✓ Can't convert invalid strings ("hello" to int will error) ✓ Float to int removes decimal part ✓ Use try-except for safe conversion ► Remember ✓ Always convert input() for mathematical operations ✓ Check data type with type() function ✓ Be careful with data loss in conversions ✓ Handle conversion errors gracefully ■ Practice Challenge 1. Get two numbers from user and calculate their average 2. Convert temperature from string to float and calculate Fahrenheit 3. Take user age as string, convert to int, check if they can vote |
