In this post, you will learn the type function in python and how does it work and also examples of type function and below is the video format of the post, check it out ????????????
What is the type () function ❓
Type function in python exactly tell what is the piece of code is, Is it a string or int, float. Mostly the type function will be used to verify the code is str or int.
And if you get any error related to the type () then it is probably called a type error.
There is also type conversion, type conversion allows the users to convert from str to int, float to int or whatever.
In simple, type conversion converts the data types.
Example of type errors
Take a look at the below piece of code, If you run this program you will see this kind of error ????????, and this is a type error.
TypeError: can only concatenate str (not “int”) to str
This means the code is not running a string with int. Usually, the str and int are like north and south pole so, in this place, we need to do type conversion to view the result.
Let’s find what type the code is
Here also I am going to use the previous example and to find the code is string or int whatever the data type it is you need to enter this code. ????????
print(type(len(input(“What is your name: “))))
The type function here says what the data type is…
Here you would wonder that I have entered the integer that is numbered and also alphabets and still you could see the same result as class int, class int is nothing but it says that this piece of code is an integer.
Even after entering an alphabet, you could see the int as result is because of len function. Then function just converts the string in a value format and display the number of characters in the value.
So, this is how to find the type of data the code is using.
Just, print the below codes and see what type you are getting.
Type conversion in python ❓
Using type conversion, we can rectify the first example error, it is really very simple. Just add which data type you wanna change.
For eg: if you need to change to str type just add in front of the code
Like this ????????
Instead, if I add float data type in front then the code will be converted to class float and this can be done using the type function.
Finally, we have seen at the beginning that the code didn’t work and let’s make it run.
I hope you enjoyed this post, see you in the next post ????????
Also Read: Swapping two variables in python
Also Read: Data types in python