In Python, type casting, also referred to as type conversion, is a technique used to transform a variable's data type into a different one to facilitate specific operations. Since Python is a dynamically typed language, it does not permit the explicit declaration of variable types by the programmer. Instead, Python infers the data types during execution time.
Let us take a look at the following example:
Example
# initializing variables
num_1 = 12 # int
num_2 = 3.6 # float
res = num_1 + num_2 # resultant value is a float
print(res, "=>", type(res))
Output:
15.6 => <class 'float'>
Explanation:
In this instance, Python has autonomously identified the data type of the resulting variable.
Nonetheless, Python offers a range of built-in functions, including int, float, and str, to carry out these type conversions explicitly when required.
Types of Python Type Casting
In Python, type casting is divided into two categories:
- Implicit Type Casting - This occurs when the Python interpreter seamlessly converts a data type to another without requiring any action from the user.
- Explicit Type Casting - In this case, the user explicitly changes the data type of a variable by employing built-in functions.
Implicit Type Conversion - The Python interpreter seamlessly changes one data type into another without requiring any input from the user.
Implicit Type Casting in Python
Implicit Type Casting, also known as Type Coercion, occurs when Python automatically converts one data type into another at runtime without requiring any intervention from the programmer.
Python adheres to a structured hierarchy of data types to facilitate safe implicit conversions. The hierarchy is outlined below:
- An integer can be converted into a floating-point number or a complex number. However, it is important to note that a complex number cannot be implicitly reverted back to an integer.
- Python refrains from performing implicit downgrades of types (for example, converting a floating-point number to an integer) since this could result in a loss of precision.
Consider the subsequent illustration of implicit type conversion in Python.
Example
# simple program to show implicit type casting
# initializing variables
a = 5 # int
b = 7.6 # float
c = 3 + 4j # complex
# implicit type casting
d = a + b # implicit conversion: int -> float
e = a + b + c # implicit conversion: int -> complex
print(d, '=>', type(d)) # returns float
print(e, '=>', type(e)) # returns complex
Output:
12.6 => <class 'float'>
(15.6+4j) => <class 'complex'>
Explanation:
In the preceding example, we have declared multiple variables of various types. Nonetheless, Python automatically adjusted their data types at runtime to ensure that the operations could be executed correctly.
Explicit Type Casting in Python
Explicit Type Casting, often referred to as Type Conversion, occurs when a developer intentionally alters the type of a variable or value by utilizing Python’s built-in functions like int, float, str, among others.
Functions of Python Type Casting
Python offers a variety of built-in functions that facilitate explicit type conversion:
| Function | Description |
|---|---|
| int() | This function converts specified variable or value to an integer (truncates decimals if x is a float). |
| float() | This function is used to convert specified variable or value to a floating-point number. |
| complex() | This function converts specified variable or value to a complex number. |
| str() | This function is utilized to convert specified variable or value to a string. |
| bool() | This function converts given variable or value to a Boolean value (True or False) |
| list() | This function is used to convert the given iterable (like string, tuple, set) to a list. |
| tuple() | This function converts the given iterable (list, string, etc.) to a tuple. |
| set() | This function is used to convert the given iterable (list, tuple, etc.) to a set. |
| dict() | This function is used to convert the given sequence of the key-value pairs to a dictionary. |
Let us discuss some of these functions with the help of examples.
Integer Conversion (int)
The int function serves the purpose of transforming a variable or value into an integer type. When applied to a floating-point variable, this function removes the decimal portion, effectively truncating the value.
Let us see the following example:
Example
# python program to convert variables and values to integers
# explicit type casting
int_1 = int(16.2) # float -> int
int_2 = int('14') # str -> int
# printing results
print(int_1, "->", type(int_1)) # decimal part is removed
print(int_2, "->", type(int_2))
Output:
16 -> <class 'int'>
14 -> <class 'int'>
Explanation:
In this instance, we employed the int function to transform the specified data type into the integer data type.
Floating-point Number Conversion (float)
The float function serves the purpose of transforming a variable or value into a floating-point number.
The example provided below demonstrates how the Python float function operates.
Example
# python program to convert variables and values to floating-point numbers
# explicit type casting
float_1 = float(19) # int -> float
float_2 = float('21.73') # str -> float
# printing results
print(float_1, "->", type(float_1)) # .0 is added as suffix
print(float_2, "->", type(float_2))
Output:
19.0 -> <class 'float'>
21.73 -> <class 'float'>
Explanation:
In this instance, we have utilized the float function to transform the specified data type into a float data type.
Complex Number Conversion (complex)
The complex function serves the purpose of transforming a variable or value into a complex number. Typically, it changes the given integer or float, denoted as x, into the form x + 0j.
Additionally, we are able to define the real and imaginary components, x and y, as the parameters of this function, which will yield a complex number represented as x + yj.
Let us explore the functionality of the complex function through the following example.
Example
# python program to convert variables and values to complex numbers
# explicit type casting
complex_1 = complex(5) # int -> complex
complex_2 = complex(8.9) # float -> complex
# printing results
print(complex_1, "->", type(complex_1)) # 0j is added
print(complex_2, "->", type(complex_2))
Output:
(5+0j) -> <class 'complex'>
(8.9+0j) -> <class 'complex'>
Explanation:
In this instance, we employed the complex function to transform the specified data type into a complex data type.
String Conversion (str)
The str function serves the purpose of transforming a variable or value into its string representation.
Let's examine the subsequent example that demonstrates how to utilize the str function.
Example
# python program to convert variables and values to strings
# explicit type casting
str_1 = str(5) # int -> str
str_2 = str(8.9) # float -> str
str_3 = str(5 + 9j) # str -> str
str_4 = str(True) # bool -> str
# printing results
print(str_1, "->", type(str_1))
print(str_2, "->", type(str_2))
print(str_3, "->", type(str_3))
print(str_4, "->", type(str_4))
Output:
5 -> <class 'str'>
8.9 -> <class 'str'>
(5+9j) -> <class 'str'>
True -> <class 'str'>
Explanation:
In this instance, we have employed the str function to transform the specified data type into a string data type.
Boolean Conversion (bool)
The built-in function bool in Python enables the conversion of a given variable or value into a Boolean representation, either True or False.
Let us see the following example:
Example
# python program to convert data type to Boolean
# explicit type casting
bool_1 = bool(0) # int -> bool
bool_2 = bool('') # str -> bool
bool_3 = bool('Example') # str -> bool
bool_4 = bool(14.5) # float -> bool
bool_5 = bool([]) # list -> bool
bool_6 = bool((1, 3, 5)) # tuple -> bool
# printing results
print(bool_1, "->", type(bool_1))
print(bool_2, "->", type(bool_2))
print(bool_3, "->", type(bool_3))
print(bool_4, "->", type(bool_4))
print(bool_5, "->", type(bool_3))
print(bool_6, "->", type(bool_4))
Output:
False -> <class 'bool'>
False -> <class 'bool'>
True -> <class 'bool'>
True -> <class 'bool'>
False -> <class 'bool'>
True -> <class 'bool'>
Type Casting in Python MCQs
- Which of the following is an explicit type conversion function in Python?
- int
- float
- str
- All of the above
Response: d) All of the above
- What will the result be when executing the subsequent code?
# python program
print(float("17.3"))
- "17.3"
- 17.3
- Error
Response: b) 17.3
- What will be the result of executing the code below?
# python program
print(int(False))
- False
- Error
Response: a) 0
- What will the result of executing the subsequent code be?
# python program
print(list("Apple"))
- "Apple"
- ['Apple']
- ['A', 'p', 'p', 'l', 'e']
- Error
Response: c) ['A', 'p', 'p', 'l', 'e']
- What will the output of this code snippet be?
# python program
print(set("224447777"))
- {'2', '4', '7'}
- {2, 7, 4}
- {'224447777'}
- {'2', '2', '4', '4', '4', '7', '7', '7', '7'}