Python : Casting

In Python, casting is the process of converting one data type to another. Python provides several built-in functions for explicit casting, allowing you to convert between different data types. Here are some common casting functions:

1. `int()` : Converts a value to an integer.


   x = int(3.14)   # x will be 3
   y = int("5")    # y will be 5

 

2. `float()` : Converts a value to a floating-point number.


   x = float(5)     # x will be 5.0
   y = float("3.14")   # y will be 3.14

 

3. `str()` : Converts a value to a string.


   x = str(5)     # x will be "5"
  y = str(3.14)  # y will be "3.14"

 

4. `bool()` : Converts a value to a boolean.


   x = bool(0)      # x will be False
   y = bool(42)     # y will be True
   z = bool("")     # z will be False

 

5. `list()` , `tuple()` , `set()` : Converts a sequence (like a list, tuple, or set) to the corresponding data type.


   x = list((1, 2, 3))    # x will be [1, 2, 3]
   y = tuple([4, 5, 6])   # y will be (4, 5, 6)
   z = set([1, 2, 3])     # z will be {1, 2, 3}

 

6. `dict()` : Converts a sequence of key-value pairs (as tuples) to a dictionary.


   x = dict([(1, 'one'), (2, 'two')])   # x will be {1: 'one', 2: 'two'}
 

7. `complex()` : Converts two numbers into a complex number.


   x = complex(1, 2)    # x will be 1 + 2j
 

These casting functions can be useful when you need to ensure that a value has a specific data type or when you want to perform operations that require a particular data type. Keep in mind that not all conversions are possible, and some conversions may result in data loss or errors if the values are not compatible.