TYPE CONVERSION
AKA Type Casting
This is the process of converting a value from one data type to another. Python provides both implicit and explicit type conversions. Implicit type conversion, or type coercion, occurs automatically when Python interprets an expression involving multiple data types, such as adding an integer to a float, where the integer is automatically converted to a float to avoid data loss. Explicit type conversion requires the programmer to manually convert a value using built-in functions like int(), float(), str(), bool(), or complex(). Type conversion is useful for ensuring compatibility between different operations, maintaining precision, and avoiding runtime errors. It also allows developers to manipulate and process data in the format most suitable for a particular computation or program requirement.
IMPLICIT
x = 7
x = x/2
print(x)
* OUTPUT: 3.5EXPLICIT
num = '12'
print(type(num));
num = int(num)
num = num + num
print(num);
print(type(num));
* OUTPUT:
<class 'str'>
24
<class 'int'>#!/usr/bin/env python3
def main() -> None:
variableInt = 5;
print(type(variableInt));
#explicitly convert the value to string
variableString = str(variableInt);
print(variableString);
print(type(variableString));
#explicitly convert the value to boolean
variableBool = bool(variableInt);
print(variableBool);
print(type(variableBool));
#explicitly convert the value to float
variableFloat = float(variableInt);
print(variableFloat);
print(type(variableFloat));
#xplicitly convert the value to complex
variableComplex = complex(variableInt);
print(variableComplex);
print(type(variableComplex));
if __name__ == "__main__":
main();
* OUTPUT
<class 'int'>
5
<class 'str'>
True
<class 'bool'>
5.0
<class 'float'>
(5+0j)
<class 'complex'> Last updated