Python Menu

Type Conversion & Type Casting in Python


Type Conversion & Casting

The Type Conversion is the process of converting the value of one data type to another data type. In general, Type Conversion classified into two types

  • Implicit Type Conversion
  • Explicit Type Conversion( Type Casting )

Implicit Type Conversion :

In Implicit type conversion, Python interpreter automatically converts one data type to another data type.In this Type Conversion the python interpreter converts lower datatype to higher datatype to avoid data loss.

 Python Example Program - Implicit Type Conversion in Python


Example: "typeconversion.py"
num1 = 15   #int
num2 = 4.5  #float

num3 = num1 + num2

print("Value of num3:",num3)
print("Datatype of num3:",type(num3))
Output: $python3 typeconversion.py
Value of num3: 19.5
datatype of num3: <class 'float'>

In the above example, we are trying to add two variable values(num1 is integer datatype & num2 is folat datatype),but resultant variable(num3) is float datatype, because python interpreter converts lower datatype(integer) to higher datatype(float) to avoid data loss.

Explicit Type Conversion ( Type Casting ) :

In Explicit type conversion, The user converts one data type to another data type.In this Type Conversion the user converts higher datatype to lower datatype or lower datatype to higher datatype.

An Explicit type conversion is also called as Type Casting in Python

Python supports following functions to perform Type Casting in Python,

Those are

  • int () : This function converts any data type to integer.
  • float() : This function is used to convert any data type to a floating point number.
  • str() : This function is used to convert any data type to a string.

 Python Example Programs - Explicit Type Conversion in Python


Example: "typecasting1.py"
a = int(2)		# returns 2
b = int(3.2)		# returns 3
c = int("6")		# returns 6
d = int("11010",2)	# returns base 2 value
print(a)
print(b)
print(c)
print(d)
Output: $python3 typecasting1.py
2
3
6
26

Example: "typecasting2.py"
a = float(2)		# returns 2.0
b = float(3.2)		# returns 3.2
c = float("6")		# returns 6.0
d = float("6.2")	# returns 6.2
print(a)
print(b)
print(c)
print(d)
Output: $python3 typecasting2.py
2.0
3.2
6.0
6.2

Example: "typecasting3.py"
a = str("abc")		# returns 'abc'
b = str(3.2)		# returns '3.2'
c = str(6)		# returns '6'
print(a)
print(b)
print(c)
Output: $python3 typecasting3.py
abc
3.2
6

Note: In Python, when an integer value is cast to float value, then it is appended with the fractional part containing zeros (0) and when a float value is cast to an integer it rounding down to the previous whole number.



Next Topic :Operators in Python