YouTip LogoYouTip

Python3 Type Conversion

## Python3 Type Conversion In Python, you often need to convert data from one type to another. Type conversion (also known as type casting) is a fundamental concept in programming. Generally, you can perform type conversion simply by using the target data type name as a constructor function. Python supports two types of type conversion: * **Implicit Type Conversion** - Performed automatically by the Python interpreter. * **Explicit Type Conversion** - Performed manually by the developer using built-in type functions. --- ## Implicit Type Conversion In implicit type conversion, Python automatically converts one data type to another without any user intervention. This typically happens during operations involving mixed data types. To prevent data loss, Python automatically promotes the lower data type (such as an integer) to a higher data type (such as a float). ### Example: Converting Integer to Float Automatically ```python num_int = 123 num_flo = 1.23 # Adding an integer and a float num_new = num_int + num_flo print("Data type of num_int:", type(num_int)) print("Data type of num_flo:", type(num_flo)) print("Value of num_new:", num_new) print("Data type of num_new:", type(num_new)) ``` **Output:** ```text Data type of num_int: Data type of num_flo: Value of num_new: 124.23 Data type of num_new: ``` **Code Analysis:** * We add two variables of different data types: `num_int` (integer) and `num_flo` (float), and store the result in `num_new`. * Python automatically converts the integer `num_int` to a float before performing the addition. * As a result, `num_new` is of type `float`. This automatic promotion avoids any loss of fractional precision. ### Example: Unsupported Implicit Conversion What happens if we try to add an integer and a string? ```python num_int = 123 num_str = "456" print("Data type of num_int:", type(num_int)) print("Data type of num_str:", type(num_str)) # This will raise an error print(num_int + num_str) ``` **Output:** ```text Data type of num_int: Data type of num_str: Traceback (most recent call last): File "test.py", line 7, in print(num_int+num_str) TypeError: unsupported operand type(s) for +: 'int' and 'str' ``` **Code Analysis:** Python cannot implicitly convert a string to an integer or vice versa for arithmetic operations. This raises a `TypeError`. To resolve this, you must use **Explicit Type Conversion**. --- ## Explicit Type Conversion In explicit type conversion (type casting), developers manually convert an object from one data type to another using predefined built-in functions such as `int()`, `float()`, and `str()`. ### Using `int()` to Cast to Integer ```python x = int(1) # x will be 1 y = int(2.8) # y will be 2 (decimal part is truncated) z = int("3") # z will be 3 (string must represent a valid integer) ``` ### Using `float()` to Cast to Float ```python x = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2 ``` ### Using `str()` to Cast to String ```python x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0' ``` ### Example: Resolving the Mixed-Type Addition By explicitly casting the string to an integer, we can safely perform the addition: ```python num_int = 123 num_str = "456" print("Data type of num_int:", type(num_int)) print("Data type of num_str before conversion:", type(num_str)) # Explicitly convert string to integer num_str = int(num_str) print("Data type of num_str after conversion:", type(num_str)) num_sum = num_int + num_str print("Sum of num_int and num_str:", num_sum) print("Data type of the sum:", type(num_sum)) ``` **Output:** ```text Data type of num_int: Data type of num_str before conversion: Data type of num_str after conversion: Sum of num_int and num_str: 579 Data type of the sum: ``` --- ## Built-in Type Conversion Functions Python provides a comprehensive set of built-in functions to perform explicit type conversions. Each function returns a new object representing the converted value. | Function | Description | | :--- | :--- | | `int(x [,base])` | Converts `x` to an integer. The optional `base` parameter specifies the numeral system base (e.g., 2, 8, 10, 16) if `x` is a string. | | `float(x)` | Converts `x` to a floating-point number. | | `complex(real [,imag])` | Creates a complex number with a real part and an optional imaginary part. | | `str(x)` | Converts object `x` into a readable string representation. | | `repr(x)` | Converts object `x` into an expression string (evaluable representation). | | `eval(str)` | Evaluates a valid Python expression represented as a string and returns the resulting object. | | `tuple(s)` | Converts a sequence `s` (like a list or string) into a tuple. | | `list(s)` | Converts a sequence `s` (like a tuple or string) into a list. | | `set(s)` | Converts a sequence `s` into a mutable set. | | `dict(d)` | Creates a dictionary. `d` must be a sequence of `(key, value)` tuples. | | `frozenset(s)` | Converts a sequence `s` into an immutable frozenset. | | `chr(x)` | Converts an integer `x` (representing a Unicode code point) to its corresponding character. | | `ord(x)` | Converts a single character `x` to its corresponding Unicode integer value. | | `hex(x)` | Converts an integer `x` into a lowercase hexadecimal string prefixed with `0x`. | | `oct(x)` | Converts an integer `x` into an octal string prefixed with `0o`. | | `bin(x)` | Converts an integer `x` into a binary string prefixed with `0b`. | | `bool(x)` | Converts object `x` to a boolean value (`True` or `False`). | | `bytes([source[, encoding[, errors]]])` | Converts an object into an immutable bytes sequence. | | `bytearray([source[, encoding[, errors]]])` | Converts an object into a mutable bytearray. | | `memoryview(obj)` | Returns a memory view object of the given argument (allows access to internal data without copying). | | `ascii(x)` | Returns a string containing a printable representation of an object, escaping non-ASCII characters using `\x`, `\u`, or `\U`. | --- ## Considerations & Best Practices 1. **Value Errors during Casting:** When explicitly casting a string to an integer or float, ensure the string contains a valid numeric representation. For example, `int("123")` works, but `int("123abc")` will raise a `ValueError`. 2. **Precision Loss:** Converting a float to an int (e.g., `int(5.9)`) does not round the number; it truncates the decimal part entirely, resulting in `5`. Use the built-in `round()` function if you need mathematical rounding. 3. **Boolean Evaluation:** In Python, empty containers (like `[]`, `()`, `{}`, `""`), the number `0`, `None`, and `False` evaluate to `False` when passed to `bool()`. Almost all other values evaluate to `True`.
← Js Class IntroRef Country Codes β†’