📖 Phase 1: Programming Fundamentals
📌 Topic 7: Type Casting
Type Casting is the process of converting a value from one data type to another.
For example, you may receive a number as a string from the user, but you need to perform mathematical operations on it. In such cases, type casting is required.
Why Do We Need Type Casting?
Type casting helps us:
• Convert user input into numbers.
• Perform mathematical calculations.
• Change data from one type to another.
• Prevent type-related errors.
Types of Type Casting
There are two types of type casting in Python:
• Implicit Type Casting (Automatic)
• Explicit Type Casting (Manual)
1. Implicit Type Casting
Python automatically converts one data type into another when it is safe to do so.
Example:
num = 10
price = 5.5
result = num + price
print(result)
print(type(result))
Output:
15.5
<class 'float'>
Python automatically converts the integer into a float.
2. Explicit Type Casting
In explicit type casting, the programmer manually converts the data type using built-in functions.
Some commonly used conversion functions are:
• int() → Converts to Integer
• float() → Converts to Float
• str() → Converts to String
• bool() → Converts to Boolean
Converting String to Integer
age = "25"
age = int(age)
print(age)
print(type(age))
Output:
25
<class 'int'>
Converting Integer to Float
marks = 90
marks = float(marks)
print(marks)
Output:
90.0
Converting Number to String
num = 100
text = str(num)
print(text)
print(type(text))
Output:
100
<class 'str'>
Converting Values to Boolean
print(bool(1))
print(bool(0))
print(bool(""))
print(bool("Python"))
Output:
True
False
False
True
Common Beginner Mistakes
❌ Trying to convert invalid values.
Example:
num = int("Hello")
This will produce an error because "Hello" is not a valid integer.
❌ Forgetting to convert user input before performing calculations.
Best Practices
✅ Convert data only when necessary.
✅ Validate user input before converting.
✅ Use the correct conversion function for the required data type.
Key Takeaways
• Type Casting means converting one data type into another.
• Python supports both Implicit and Explicit type casting.
• int(), float(), str(), and bool() are the most commonly used conversion functions.
• Always convert user input before performing mathematical operations.
• Understanding type casting helps you write error-free and efficient programs.
➡️ Double Tap ❤️ For More