Python Type Conversion

Type Conversion in Python

Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive programming. This article is aimed at providing information about certain conversion functions.

There are two types of Type Conversion in Python:

Let’s discuss them in detail.

Implicit Type Conversion

In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data type to another without any user involvement. To get a more clear view of the topic see the below examples.

Example:

 x =10
 
print("x is of type:",type(x))
 
y =10.6
print("y is of type:",type(y))
 
x =x +y
 
print(x)
print("x is of type:",type(x))

Output:

 x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
x is of type: <class 'float'>

As we can see the type od ‘x’ got automatically changed to the “float” type from the “integer” type. this is a simple case of Implicit type conversion in python.

Explicit Type Conversion

In Explicit Type Conversion in Python, the data type is manually changed by the user as per their requirement. Various form of explicit type conversion are explained below: 

1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which string is if the data type is a string.2. float(): This function is used to convert any data type to a floating-point number . 

Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods:

Example

Convert from one type to another:

 
x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:

  a = float(x)

#convert from float to int:

  b = int(y)

#convert from int to complex:
c = complex(x)

print(a)
print(b)

  print(c)

print(type(a))
print(type(b))

  print(type(c))

Note: You cannot convert complex numbers into another number type.

Related Pages

For more, checkout Geeks For Geeks and W3Schools.