|
| 1 | +<div align="center"> |
| 2 | + <img src="https://github.com/Vibhav1207/Python-Course/blob/main/assets/typecasting.png?raw=true"> |
| 3 | +</div> |
| 4 | + |
| 5 | +--- |
| 6 | +## 📚 Table of Contents |
| 7 | + |
| 8 | +- [Type Casting](#-type-casting) |
| 9 | +- [Explicit Type Casting](#-explicit-type-casting) |
| 10 | +- [Implicit Type Casting](#-implicit-type-casting) |
| 11 | + |
| 12 | +## 🔄 Type Casting |
| 13 | + |
| 14 | +Type Casting is the conversion of one data type into another data type. Python provides various built-in functions for type conversion, such as `int()`, `float()`, `str()`, `ord()`, `hex()`, `oct()`, `tuple()`, `set()`, `list()`, and `dict()`. |
| 15 | + |
| 16 | +There are two types of Type Casting in Python: |
| 17 | +1. Explicit Type Casting (Manual Conversion) |
| 18 | +2. Implicit Type Casting (Automatic Conversion) |
| 19 | + |
| 20 | +## 🎯 Explicit Type Casting |
| 21 | + |
| 22 | +Explicit Type Casting, also known as Type Conversion, is performed manually by the programmer using Python's built-in functions. This is done when you want to specifically convert one data type to another. |
| 23 | + |
| 24 | +### Common Type Conversion Functions |
| 25 | + |
| 26 | +```python |
| 27 | +# Converting string to integer |
| 28 | +string_num = "15" |
| 29 | +number = int(string_num) # number = 15 |
| 30 | + |
| 31 | +# Converting integer to float |
| 32 | +int_num = 7 |
| 33 | +float_num = float(int_num) # float_num = 7.0 |
| 34 | + |
| 35 | +# Converting number to string |
| 36 | +num = 123 |
| 37 | +string = str(num) # string = "123" |
| 38 | +``` |
| 39 | + |
| 40 | +### Example of Explicit Type Casting |
| 41 | + |
| 42 | +```python |
| 43 | +# Adding string number with integer |
| 44 | +string = "15" |
| 45 | +number = 7 |
| 46 | +string_number = int(string) # Converting string to integer |
| 47 | +sum = number + string_number |
| 48 | +print("The Sum of both the numbers is:", sum) # Output: The Sum of both the numbers is 22 |
| 49 | +``` |
| 50 | + |
| 51 | +## 🔄 Implicit Type Casting |
| 52 | + |
| 53 | +Implicit Type Casting is automatically performed by Python interpreter when: |
| 54 | +1. We perform operations between different data types |
| 55 | +2. Python needs to convert a smaller data type to a higher data type to prevent data loss |
| 56 | + |
| 57 | +### Data Type Hierarchy |
| 58 | +Python follows a hierarchy in data types where some types are "higher" than others: |
| 59 | +- Boolean → Integer → Float → Complex |
| 60 | + |
| 61 | +### Example of Implicit Type Casting |
| 62 | + |
| 63 | +```python |
| 64 | +# Integer and Float addition |
| 65 | +a = 7 # Integer |
| 66 | +print(type(a)) # Output: <class 'int'> |
| 67 | + |
| 68 | +b = 3.0 # Float |
| 69 | +print(type(b)) # Output: <class 'float'> |
| 70 | + |
| 71 | +# Python automatically converts result to float |
| 72 | +c = a + b # Integer + Float = Float |
| 73 | +print(c) # Output: 10.0 |
| 74 | +print(type(c)) # Output: <class 'float'> |
| 75 | +``` |
| 76 | + |
| 77 | +### Common Implicit Type Casting Scenarios |
| 78 | + |
| 79 | +```python |
| 80 | +# Integer and Float |
| 81 | +result1 = 5 + 3.14 # Result is float (8.14) |
| 82 | + |
| 83 | +# Integer and Complex |
| 84 | +result2 = 10 + 2j # Result is complex (10+2j) |
| 85 | + |
| 86 | +# Boolean and Integer |
| 87 | +result3 = True + 1 # Result is integer (2) |
| 88 | +``` |
| 89 | + |
| 90 | +## 🔄 Collection Type Casting |
| 91 | + |
| 92 | +Python allows type casting between different collection types (list, tuple, set, dict). Here are some common scenarios: |
| 93 | + |
| 94 | +```python |
| 95 | +# Converting between lists and tuples |
| 96 | +my_list = [1, 2, 3] |
| 97 | +my_tuple = tuple(my_list) # (1, 2, 3) |
| 98 | +back_to_list = list(my_tuple) # [1, 2, 3] |
| 99 | + |
| 100 | +# Converting to set (removes duplicates) |
| 101 | +duplicates_list = [1, 2, 2, 3, 3, 4] |
| 102 | +unique_set = set(duplicates_list) # {1, 2, 3, 4} |
| 103 | + |
| 104 | +# Converting dictionary keys/values to list |
| 105 | +my_dict = {"a": 1, "b": 2} |
| 106 | +keys_list = list(my_dict.keys()) # ["a", "b"] |
| 107 | +values_list = list(my_dict.values()) # [1, 2] |
| 108 | +``` |
| 109 | + |
| 110 | +## 🌟 Real-World Applications |
| 111 | + |
| 112 | +### 1. Data Processing |
| 113 | +```python |
| 114 | +# Converting CSV data to appropriate types |
| 115 | +user_id = "1001" # From CSV as string |
| 116 | +age = "25" # From CSV as string |
| 117 | + |
| 118 | +# Converting to proper types for processing |
| 119 | +processed_id = int(user_id) |
| 120 | +processed_age = int(age) |
| 121 | +``` |
| 122 | + |
| 123 | +### 2. API Response Handling |
| 124 | +```python |
| 125 | +# Converting JSON response data |
| 126 | +api_response = {"temperature": "24.5", "is_sunny": "true"} |
| 127 | + |
| 128 | +# Converting to appropriate types |
| 129 | +temp = float(api_response["temperature"]) |
| 130 | +is_sunny = api_response["is_sunny"].lower() == "true" |
| 131 | +``` |
| 132 | + |
| 133 | +## ⚡ Performance Considerations |
| 134 | + |
| 135 | +1. **Memory Usage**: |
| 136 | + - Converting large collections can consume significant memory |
| 137 | + - Consider using generators for large datasets |
| 138 | + |
| 139 | +2. **Processing Time**: |
| 140 | + - Implicit casting is generally faster than explicit casting |
| 141 | + - Avoid unnecessary type conversions in loops |
| 142 | + |
| 143 | +```python |
| 144 | +# Less efficient (type conversion in loop) |
| 145 | +for i in range(1000): |
| 146 | + str_num = str(i) # Unnecessary conversion |
| 147 | + process(str_num) |
| 148 | + |
| 149 | +# More efficient (convert once) |
| 150 | +str_nums = [str(i) for i in range(1000)] |
| 151 | +for num in str_nums: |
| 152 | + process(num) |
| 153 | +``` |
| 154 | + |
| 155 | +## 🚨 Important Notes |
| 156 | + |
| 157 | +1. Not all type conversions can be done implicitly. Python will raise a TypeError if the conversion is not possible. |
| 158 | +2. Explicit type casting gives you more control but can raise errors if the conversion is not valid. |
| 159 | +3. When working with numeric types, Python automatically converts to the type that can best preserve the information. |
| 160 | +4. String to number conversion must always be done explicitly using `int()` or `float()`. |
| 161 | +5. Always validate data before type casting to handle potential errors gracefully. |
| 162 | +6. Consider using specialized libraries (like `numpy`) for efficient numerical type conversions. |
| 163 | +7. Be cautious when converting floating-point numbers to integers as it may lead to data loss. |
0 commit comments