Updated July 24, 2023
Introduction to Type Casting in Python
Type casting is a method used to change the variables/ values declared in a certain data type into a different data type to match the operation required to be performed by the code snippet. In python, this feature can be accomplished by using constructor functions like int(), string(), float(), etc. The type casting process’s execution can be performed by using two different types of type casting, such as implicit type casting and explicit type casting.
Types of Casting in Python
Python has two types of type conversion:
1. Implicit Type casting
Implicit type conversion is performed automatically by the interpreter, without user intervention. Python automatically converts one data type to another data type. This process doesn’t need any user involvement Python promotes the conversion of lower data type, for example, integer to higher data type says float to avoid data loss. This type of conversion or type casting is called UpCasting.
2. Explicit Type casting
In Explicit Type conversion, the user or programmer converts the data type of an object to the required data type. In Python we use predefined functions like int(), float(), str(), bool() etc to perform explicit type conversion.
Syntax:
(Required datatype) (Expression)
↓
(Desired type)
Examples of Type Casting in Python
Below are the examples of type casting in python:
Example # 1 – Implicit Type Conversion/Casting
Program to illustrate Implicit Type conversion/casting.
Python file: Example1.py
# Program to illustrate Implicit type conversion
# creating addition() function to add two numbers
def addition(a, b):
print("Type of first number(a) :", a, type(a))
print("Type of second number(b) :", b, type(b))
c = a + b
print("Type of resulting variable(c) :", c, type(c))
# addition() function calls with different inputs
addition(21, 23) # both integers
print('\n')
addition(21, 23.0) # second being float
print('\n')
addition(21.0, 23) # first being float
print('\n')
addition(21.0, 23.0) # both float
Output: Example1.py
Explanation:
The function to add two numbers is defined. Type of first input number, second input number and the type of summation is printed.
- The first call of addition(): Both input numbers are of integer type, so the result is also an integer. No type casting is needed in this case.
- The second call of addition(): First input is an integer, and the second input is of floating type. So python interpreter internally converts the integer type to float type to avoid data loss. Therefore, the result is floating type, as shown in the above output.
- The third call of addition(): First input is a floating number, and the second input is of integer type. So python interpreter internally converts the integer type to float type to avoid data loss. Therefore, the result is a floating type.
- The fourth call of addition(): Both numbers are of floating type. So python interpreter will not perform any type of conversion here. Therefore, the result is a floating type.
Example #2 – Explicit Type Conversion
Following is an illustration of the Explicit type conversion.
Python file: Example2.py
# Program to illustrate Explicit type conversion
# creating addition() function to add two numbers
def addition(a, b):
print("Type of first number(a) :", a, type(a))
print("Type of second number(b) :", b, type(b))
c = a + b
print("Type of resulting variable(c) :", c, type(c))
print("accepting input from the user -->")
print("Enter first number")
num1 = input()
print("Enter second number")
num2 = input()
# addition() function call
addition(num1, num2)
print('\n')
Output: Example2.py
Explanation:
- In the above program, the addition() function is defined, which will compute the summation of two numbers. The user is prompted to enter two numbers through input() statements.
- Finally, addition() is called with numbers 23 and 18. But the result is 2318 as shown in the below output and not 41. Why??
- This is because the return type of input() is a string. Therefore, the numbers entered by the user are treated as string values. So, the output is the concatenation of string rather than a summation of integers which is the expected output. In this case, Python will not perform any type casting itself. This can be corrected with Explicit type conversion.
Above Code Can Be Modified As:
# Program to illustrate Explicit type conversion
# creating addition() function to add two numbers
def addition(a, b):
print("Type of first number(a) :", a, type(a))
print("Type of second number(b) :", b, type(b))
c = a + b
print("Type of resulting variable(c) :", c, type(c))
# addition() function calls with different inputs
print("accepting input from the user -->")
print("Enter first number")
# Explicit typecasting
num1 = int(input())
print("Enter second number")
num2 = int(input())
# addition() function call
addition(num1, num2)
print('\n')
Here, in this program int(input()) will convert the string to the integer type. Therefore, we’ll get the desired output as shown below:
Output:
Example #3 – Explicit Type casting Using Constructor Functions
Explicit Type casting using constructor functions like int(), float(), str() etc.
Python file: Example3.py
# Explicit Type conversion using constructor functions
# 1 --> Converting to integer type using int()
print("1: converting to integer type")
print(int(9.6)) # float to int
print(int(True)) # bool to int
print(int(False)) # bool to int
print("123") # str to int
print('\n')
# 2 --> converting to float type using float()
print("2: converting to floating type")
print(float(12)) # int to float
print(float(True)) # bool to float
print(float(False)) # bool to float
print(float("123")) # string to float
print('\n')
# 3 --> converting to bool type using bool()
print("3: converting to boolean type")
print(bool(12)) # integer to bool
print(bool(0.0)) # float to bool
print(bool([1,2,3])) # list to bool
print(bool()) # tuple to bool
print('\n')
# 4 --> converting to string type using str()
print("4: converting to string type")
print(str(123)) # integer to string
print(str(12.12)) # float to string
print(str([10, 20, 30])) # list to strings
Output: Example3.py
Conclusion
Time and again, there is a need to convert a value of one data type to another in any programming language. Python offers both Implicit type and Explicit type conversions.
A python interpreter performs implicit type conversion without programmer intervention. The programmer performs an explicit type conversion.
Recommended Articles
This is a Guide to Type Casting in Python. Here we discuss the basic concept, two different types and various examples of casting in python. You may also look at the following articles to learn more –