Page 72 - IPP-11
P. 72

  Explicit Conversion


                   Explicit conversion, also called type casting, happens when data type conversion takes place
                   deliberately, i.e., the programmer forces it in the program. The general form of an explicit
                   data type conversion is:
                   (new_data_type) (expression)

                   With explicit type conversion, there is a risk of data loss since we are forcing an expression
                   to be of a specific type.
                   For example, converting a floating value of x = 50.75 into an integer type, i.e., int(x), will
                   discard the fractional part .75 and shall return the value as 50.
                    >>> x = 50.75
                    >>> print(int(x))
                    50

                   Following are some of the functions in Python that are used for explicitly converting an
                   expression or a variable into a different type:

                                   Table 3.5: Explicit type conversion functions in Python
                                   Function                         Description
                             int(x)                   Converts x into an integer.
                             float(x)                 Converts x into a floating-point number.
                             str(x)                   Converts x into a string representation.
                             chr(x)                   Converts x into a character.

                  Implicit Conversion

                   Implicit conversion, also known as coercion, happens when data type conversion is done
                   automatically by Python and is not instructed by the programmer.

              Example 5: Program to illustrate implicit type conversion from int to float.                        Python Programming Fundamentals (Additions)





















              In the above example, an integer value stored in variable num1 is added to a float value stored in
              variable num2, and the result gets automatically converted into a float value stored in variable
              sum1 without explicitly telling the system. This is an example of implicit data conversion.
              The reason for the float value not converted into an integer instead is due to type promotion
              that allows performing operations (whenever possible) by converting data into a wider-sized
              data type without any loss of information.

                                                                                                              3.3
   67   68   69   70   71   72   73   74   75   76   77