Type Casting in Python

Type Casting in Python

What is Type Casting?

Type Casting is the method to convert the variable data type into another data type in order to the operation required to be performed by users.

Types of Type Casting

  1. Implicit Type Casting
  2. Explicit Type Casting

Implicit Type Casting

In Implicit Type Casting Python converts data type into another data type automatically. In this process, users don’t have to involve in this process.

Example

INT

a = 5
print(type(a))
#<class 'int'>

FLOAT

b = 8.5
print(type(b))
#<class 'float'>

FLOAT ADDITION

#Python automatically converts
#c to float as it is a float addition
c = 5 + 3.0
print(c)
#8.0
print(type(c))
#<class 'float'>

FLOAT ADDITION

#Python automatically converts
#d to float as it is a float addition
d = a + b
print(d)
#13.5
print(type(d))
#<class 'float'>    

FLOAT MULTIPLICATION

#Python automatically converts
#e to float as it is a float multiplication
e = a * b
print(e)
#42.5
print(type(e))
#<class 'float'>

Explicit Type Casting

In Explicit Type Casting Python needs user involvement to convert the variable data type into a certain data type in order to the operation required.

Example

INT TO FLOAT

# int variable
a = 9
#explicit typecast to float
b = float(a)
print(b)
#9.0
print(type(b))
#<class 'float'>

FLOAT TO INT

# float variable
c = 9.5
#explicit typecast to int
d = int(c)
print(d)
#9
print(type(d))
#<class 'int'>

INT TO STRING

# int variable
e = 9
#explicit typecast to str
f = str(e)
print(f)
#9
print(type(f))
#<class 'str'>

STRING TO INT

# str variable
g = "8"
#explicit typecast to int
h = int(g)
print(h)
#8
print(type(h))
#<class 'int'>

STRING TO FLOAT

# str variable
i = "8.5"
#explicit typecast to float
j = int(i)
print(j)
#8.5
print(type(j))
#<class 'float'>

Did you find this article valuable?

Support Prahlad Inala by becoming a sponsor. Any amount is appreciated!