Type Conversion
Type Conversion in Python means changing one data type into another so the program can use data properly.
For example:
- Converting text into a number
- Converting a number into text
This helps Python perform calculations and avoid errors.
Example
x = "10"
y = int(x)
print(y + 5)
Output
15
The string "10" is converted into an integer.
Real-Life Analogy
Think of type conversion like changing money:
- Coins into notes
- Rupees into dollars
The value stays the same, but the form changes.
In the same way, Python changes one data type into another.
Why Do We Use Type Conversion?
Type conversion helps us:
- Perform calculations
- Work with different data types
- Prevent errors
- Make programs accurate
Types of Type Conversion
There are two types of type conversion:
- Implicit Type Conversion (Automatic)
- Explicit Type Conversion (Manual)
1. Implicit Type Conversion (Automatic)
What is Implicit Conversion?
Implicit conversion happens automatically by Python.
When different data types are used together, Python may convert one type automatically.
Example
x = 5
y = 2.5
result = x + y
print(result)
Output
7.5
Python converts:
5 → 5.0
automatically.
About Implicit Conversion
- Done automatically
- No function needed
- Happens during operations
2. Explicit Type Conversion (Manual)
What is Explicit Conversion?
Explicit conversion means manually changing a data type using functions.
Python provides built-in conversion functions.
Common Conversion Functions
int()→ Converts to integerfloat()→ Converts to floatstr()→ Converts to stringbool()→ Converts to boolean
Examples of Explicit Conversion
Convert String to Integer
x = "10"
y = int(x)
print(y + 5)
Output:
15
Convert Integer to Float
x = 10
y = float(x)
print(y)
Output:
10.0
Convert Number to String
x = 25
y = str(x)
print(y)
Output:
25
Practical Example
Think of type conversion like converting:
- Liters to milliliters
- Numbers into words
Python also converts data types when needed.
Implicit vs Explicit Conversion
| Implicit Conversion | Explicit Conversion |
|---|---|
| Automatic | Manual |
| No function needed | Uses functions |
| Happens during operations | Done when required |
Invalid Conversion Example
x = "hello"
y = int(x)
This gives an error because text cannot be converted into a number.
Common Beginner Mistakes
- Converting text like "hello" into numbers
- Forgetting to use conversion functions
- Mixing wrong data types
- Not checking data type before conversion
➤ Key Points
- Type conversion changes one data type into another
- Two types: Implicit and Explicit
- Implicit conversion is automatic
- Explicit conversion is manual
- Helps avoid errors in programs
➤ Tips
- Use int(), float(), str() when needed
- Check data types before converting
- Be careful converting strings into numbers
- Practice different conversions