Typecasting in Python
'''
Typecasting in Python:
The conversion of data types in Python is known as type casting.
Python supports a wide variety of functions or methods like:
int(), float(), str(), ord(), hex(), oct(), tuple(), set(), list(), dict() etc. for the type casting in Python.
'''
a="1"
b="2"
print(a+b) #output=12
# We can see the output is 12 because the value of a and b are strings.
print(int(a)+int(b)) #output=3
#We can see the output is 3 because now the values of a and b has become integer functions.
'''Either two integer functions or two string functions or any two functions of the same data type can be operated to get the result.'''
'''
Two types of typecasting:
1. Explicit Conversion (Explicit typecasting in Python)
2. Implicit Conversion (Implicit typecasting in Python)
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.
It can be done by using the int(), float(), hex(), oct(), str() etc. functions.
Implicit Typecasting:
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 operation on variables with different data types in Python, one of the variable's data types will be changed to the higher data type. According to the level, one data type is converted into other by the Python interpreter itself (automatically). This is called implicit data type.
'''
#Explicit-Hum kar rahe hein
#Implicit- Python khud kar raha hai
#Example of Explicit Typecasting:
# string="15"
# number=7
# string_number=int(string) i.e. int(15)=15
'''It throws an error if the string is not a valid integer
i.e. there will be a syntax error if we add "15"+7
'''
#Sum= 15+7=22
#print("The sum of both the numbers is: ",sum)
#Example of Implicit Typecasting:
a=1.9
b=9
print(a + b) #output=10.9
print("The type of (a+b) is", type (a+b)) #output=10.9 <class 'float'>
Comments
Post a Comment