Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 122 - 2612_Digimind
P. 122

    Implicit type conversion: Python automatically converts one data type to another when there
                         is no risk of data loss. This process is known as implicit type conversion or automatic type
                         casting.

                      For example,
                          Program1.py

                       File  Edit  Format    Run   Options   Window    Help

                       num_int = 10 # Integer
                       num_float = 10.5  # Float
                       result = num_int + num_float # Integer is converted to Float
                       print(result)
                       print(type(result))

                          Output

                        20.5
                        <class 'float'>

                      In the above program, Python automatically converts num_int (an integer) into a float before

                      performing addition. The result is stored as a float to avoid loss of precision.
                         Explicit Type Conversion: This type of conversion is done manually using built-in functions.
                        The user specifies the required data type using type conversion functions.

                        Common functions:
                        o  int() → Converts to integer

                        o  float() → Converts to float
                        o  str() → Converts to string
                      For example,

                          Program2.py
                       File  Edit  Format    Run   Options   Window    Help

                       num_str = "100"  # String
                       num_int = int(num_str)  # Convert to Integer
                       print(num_int)
                       print(type(num_int))

                          Output

                        100
                        <class 'int'>

                      120   Premium Edition-VII

| 117 118 119 120 121 122 123 124 125 126 127 |