21/10/2024, 13:11 Python
Python - Lecture 9 : Type Casting
# TypeCasting - The conversion of one data into the other data type is known as type casting in python or
type conversion in python.
Eg:
#a = "1"
#b = "2"
a = 1
b = 2
print(a + b)
Two Types of TypeCasting :
1. Explicit Conversion - "Conversion did by user"
2. Implicit Conversion - "Python is doing by it's own"
Explicit typecasting:
The conversion of one data type into another data type, done via developer or programmer's intervention or
manually as per the requirement, is known as explicit type conversion.
Example of explicit typecasting:
string = "15"
number = 7
string_number = int(string) #throws an error if the string is not a valid integer
sum= number + string_number
print("The Sum of both the numbers is: ", sum)
Output:
The Sum of both the numbers is 22
Implicit type casting:
Data types in Python do not have the same level i.e. ordering of data types is not the same in Python. Some of
the data types have higher-order, and some have lower order. While performing any operations on variables
with different data types in Python, one of the variable's data types will be changed to the higher data type.
https://notebook.zoho.in/app/index.html#/notebooks/dcr5z062df283b6d34515b57bede07611926f/notecards/9wn9o8cb9c264ea9d48ad9b58f05f2aa53c11 1/2
21/10/2024, 13:11 Python
According to the level, one data type is converted into other by the Python interpreter itself (automatically).
This is called, implicit typecasting in python.
Example of implicit type casting:
# Python automatically converts
# a to int
a = 7
print(type(a))
# Python automatically converts b to float
b = 3.0
print(type(b))
# Python automatically converts c to float as it is a float addition
c = a + b
print(c)
print(type(c))
Output:
<class 'int'>
<class 'float'>
10.0
<class 'float'>
https://notebook.zoho.in/app/index.html#/notebooks/dcr5z062df283b6d34515b57bede07611926f/notecards/9wn9o8cb9c264ea9d48ad9b58f05f2aa53c11 2/2