Python Type Casting

You can convert one data type value into another. This conversion is called Type Casting or Type Conversion.

The following are various inbuilt functions for type casting.

  • int()
  • float()
  • complex()
  • bool()
  • str()


You can use this function to convert values from other types to int. You can convert from any type to int except complex type.

a = int(1)             # a will be 1
b = int(2.8)        # b will be 2
b = int("3")        # c will be 3
d = int(10+5j)   # TypeError: can't convert complex to int


You can use float() function to convert other type values to float type. You can convert any type value to float type except complex type.

x = float(1)                     # x will be 1.0
y = float(2.8)                 # y will be 2.8
z = float("3")                 # z will be 3.0
w = float("4.2")            # w will be 4.2
v = float(10+5j)            # TypeError: can't convert complex to float


You can use complex() function to convert other types to complex type.

complex(10)                        ==>  10+0j
complex(10.5)                    ==>   10.5+0j
complex(True)                   ==>   1+0j
complex(10,-2)                   ==>   10-2j
complex(True,False)       ==>   1+0j
complex("10")                    ==>   10+0j


You can use this function to convert other type values to bool type.

bool(0)                ==> False
bool(10)              ==> True
bool(10.5)          ==> True
bool(0.178)        ==> True
bool(0.0)           ==> False
bool(10-2j)        ==> True
bool(0+0j)        ==> False
bool("True")    ==> True
bool("False")   ==> True
bool("")              ==> False


You can use this method to convert other type values to str type.

a = str("s1")     # a will be 's1'
b = str(2)          # b will be '2'
c = str(3.0)      # c will be '3.0'

Previous Read : Python Numbers

Share on:

Ravindra Kumar

Hi, This is Ravindra. I am founder of TheCodeCloud. I am AWS Certified Solutions Architect Associate & Certified in Oracle Cloud as well. I am DevOps and Data Science Enthusiast.

Recommended Reading..

1 thought on “Python Type Casting”

Leave a Comment