Page 281 - Ai_C10_Flipbook
P. 281

Type Conversion

                 Type conversion is the process of converting the value of one data type into another data type to match the
                 operation required to be performed by the code. Python supports two different types of type conversion.
                 Implicit Type Conversion

                 When the process of converting the value of one data type into another data type is done automatically without
                 involving any action from the programmer is called Implicit Type conversion. Python always converts smaller
                 data types to larger data types to avoid the loss of data.

                 [1]:   a = 5
                        print("The datatype of a is :",type(a) )
                        b = 6.5
                        print("The datatype of b is :",type(b))
                        a=a+b
                        print("Value of a after addition is :",a)
                        print("Datatype of a after addition is :", type(a))
                        The datatype of a is : <class 'int'>
                        The datatype of b is : <class 'float'>
                        Value of a after addition is : 11.5
                        Datatype of a after addition is : <class 'float'>
                 Explicit Type Conversion

                 Explicit type conversion is also called typecasting because the programmer does the type conversion/casting
                 exclusively by changing the data types of the objects using the predefined functions like int(), float(),
                 str(),bool() etc. For example:


                 [1]:   float(12)
                        12.0


                 [2]:   int(5.5)
                        5


                 [3]:   str(12)
                        '12'


                 [4]:   bool(0)
                        False
                 The print() Function


                 The print() function is used to display an output on the screen. It converts the expressions into a string
                 before writing to the screen. Syntax of the print() function is:

                    print(object(s), sep=separator, end=end)
                 Where,

                    • object can be one or more separated by comma and it can be a variable, literal or an expression. An object
                   will be converted to string before printed. It is optional.
                    • sep, if there are more than one objects then it will tell how to separate those objects. Default is space '  '. It
                   is optional.
                    • end it specify what to print at the end. Default is newline ‘\n’. It is optional.

                                                                                    Advance Python (Practical)  279
   276   277   278   279   280   281   282   283   284   285   286