Introduction
On day 9 of my python coding journey, I learned about typecasting in python, and types of typecasting and wrote a small code to test typecasting in python.
So let's get started......
What is Typecasting?
The conversion of one datatype into another datatype is known as Typecasting or type conversion in python.
There are 2 types of typecasting viz:
Explicit typecasting
Implicit typecasting
Explicit Typecasting
The conversion of one datatype into another datatype, done by the programmer at his will or as per project requirement, is known as "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)
The Sum of both the numbers is 22
Implicit Typecasting
Datatypes in Python do not have the same level, i.e the order of datatypes is not the same. Some datatypes may be of higher order while others may be of lower order. So while performing operations on variables the lower order datatypes are converted to higher order datatypes, and then it is called Implicit typecasting. According to the level of the datatype, it is automatically converted into a higher order by the python interpreter.
# 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'>
Example
a = "1"
a = 1
b = "2"
b = 2
print (a+b , ", this is without typecasting") #without typecasting
print(int(a) + int(b), ", this is with typecasting") #after typecasting
#Implicit TypeCasting
c = 1.9
d = 8
print(c + d)
output
12 , this is without typecasting
3 , this is with typecasting
9.9
Resources Used
Conclusion
Thanks, guys for going through this blog post. Through this blog, we learnt about how typecasting works and how the data type of the variables can be changed based on their usage.
Thank you if you read this post and have found this post useful of my learnings from Day #9 of python
See you in the next one.....
About Me
Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practising coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.
I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.
So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.