Python Type conversion


TYPE CONVERSION

Type Conversion converts the object from one data type to another data type.

Implicit Type Conversion

It is performed automatically by the Python interpreter. Loss of data is avoided in Implicit Type Conversion.

Changing the value of one data type (such as integer, string, float, etc.) to a different data type is called type conversion. It is beneficial in day-to-day and competitive programming.

Implicit Type Conversion:

It is a process in which a data type is automatically converted into another data type, and it does not require any user engagement.

Explicit Type Conversion:

It is manually converted by the user according to the demands. In this type of Conversion, users convert the data type of an object to the needed data type accordingly.

A different form of an explicit type of Conversion are:-


    int(a, base): It changes all data types to an integer. 'Base' is where the string is if the data type is of string data type.

    float(): It changes any data type to a floating-point number.

    ord(): It changes a character to an integer.

    hex(): It changes an integer to a hexadecimal string.

    oct(): It changes an integer to an octal string. 

    tuple(): It changes to a tuple.

    set(): It returns the type after changing to set.

    list(): It changes a data type to a list type.

    dict(): It converts a tuple of order (such as key, value) into a dictionary.

    str() : It changes an integer into a string.

    complex(real,imag) : It changes real numbers to complex(real,imag) numbers.

    chr(number): It changes a number to its identical ASCII character.

Here, since the float is a higher datat ype, python interpreter automatically converses into the higher data type that is float. The same happens for string(higher data type) and integer(lower data type).

Explicit Type Conversion

is also called Type Casting, the user converts the data types of objects using predefined functions. In Type Casting, loss of data may occur as we forcibly convert the object to be of a specific data type.

Example:

x = float(1) y = int(2.8) z = complex(x) print(x) print(y) print(z) print(type(x)) print(type(y)) print(type(z))

OUTPUT:

1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>