Typecasting in PythonIn this tutorial, we will learn how typecasting happens in Python. We come across different kinds of arithmetic operations in which multiple data types are involved and then results are obtained accordingly. Here we will discuss both,
Let’s understand them with the help of programs- Implicit Type ConversionDuring the implicit type conversion, the user is not supposed to mention any specific data type during the conversion. The following program illustrates how it can be done in Python. Output: 10 The type of a is <class 'int'> 4.5 The type of b is <class 'float'> 4.0 The type of c is <class 'float'> 5.0 The type of d is <class 'float'> The product of a and b is 45.0 The addition of c and d is 9.0 Explanation- Let’s have a glance at the explanation of this program.
Now, it’s time to move on to the next thing which is explicit type conversion. Explicit Type ConversionIn this type conversion, the user is supposed to pass the value in a function to obtain the required data type. The int(), float() and str() are mostly used for the explicit type conversion. Consider the program given below, Output: The type of 'a' before typecasting is <class 'float'> 10 The type of 'a' after typecasting is <class 'float'> The type of 'b' before typecasting is <class 'float'> 8 The type of 'b' after typecasting is <class 'float'> The type of 'c' before typecasting is <class 'int'> 7.0 The type of 'c' after typecasting is <class 'int'> Explanation- Let’s understand what we have done in this program.
Finally, let us have a look at the last program of this article that covers possible types of explicit type conversions. Output: The type of 'a' before typecasting is <class 'int'> 10 The type of 'a' after typecasting is <class 'int'> The type of 'b' before typecasting is <class 'str'> 8 The type of 'b' after typecasting is <class 'str'> The type of 'c' before typecasting is <class 'str'> 7.9 The type of 'c' after typecasting is <class 'str'> Explanation- The approach is similar to the above program and in this program, we have included conversion using all the three int(), str(), and float(). ConclusionIn this tutorial, we learned what is typecasting in python, what are its types, and how it can be performed in Python. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263356.html