Data Structures In Python 3

Data Type Conversion

Sometimes, we are required to convert an integer to a float or vice versa, for example. Or maybe you find out that you have been using an integer when what you really need is a float. In such cases, you can convert the data type of variables.

To check the type of an object in Python, use the built-in type() function, just like in the lines of code below:

a = 10
print(type(a))
b=23.45
print(type(b))
c=True
print(type(c))
d=2+4j
print(type(d))

Output:

#Output:

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'complex'>
>>> 

Typecasting / Casting

When you change the type of an entity from one data type to another, this is called “typecasting”. There can be two kinds of data conversions possible: implicit termed as coercion and explicit, often referred to as casting.

Implicit Data Type Conversion

This is an automatic data conversion and the compiler handles this for you. Take a look at the following examples:

 

# a is  float
a = 4.0 
# b is an integer
b = 2 
# Divide a by b
c = a/b
print("a = ",a)
print("b = ",b)
print("c = ",c)
# Check the type of variable
print(type(a))
print(type(b))
print(type(c))

Output:

#Output:

a =  4.0
b =  2
c =  2.0
<class 'float'>
<class 'int'>
<class 'float'>
>>> 

Explicit Data Type Conversion

This type of data type conversion is user defined, which means you have to explicitly inform the compiler to change the data type of certain entities. Consider the code chunk below to fully understand this:

# a is  inteter
a = 4
# b is a string
b = "2" 
# On adding a and b
c = a+b
print("a = ",a)
print("b = ",b)
print("c = ",c)

Output:

Error gets generated as b is a string and cannot be directly added to a.

Modified program

# a is  inteter
a = 4
# b is a string
b = "2" 
# On adding a and b
c = a+int(b)
print("a = ",a)
print("b = ",b)
print("c = ",c)
# Check the type of variable
print(type(a))
print(type(b))
print(type(c))

Output:

#Output:

a =  4
b =  2
c =  6
<class 'int'>
<class 'str'>
<class 'int'>
>>> 
# a is  string
a = "My Age is "
# b is a string
b = 10 
# On adding a and b
c = a + b 
print("a = ",a)
print("b = ",b)
print("c = ",c)
# Check the type of variable
print(type(a))
print(type(b))
print(type(c))

Output:

An error gets generated as b is string and cannot be directly added to a.

Modified program

# a is  string
a = "My Age is "
# b is a string
b = 10 
# On adding a and b
c = a + str(b )
print("a = ",a)
print("b = ",b)
print("c = ",c)
# Check the type of variable
print(type(a))
print(type(b))
print(type(c))

#Output:
a =  My Age is 
b =  10
c =  My Age is 10
<class 'str'>
<class 'int'>
<class 'str'>
>>> 

Visitor Counter

0051036