What is Type Coercion or Type Casting?
When we convert a variable or one Data Type to another data type, it is called Type Coercion or Type Casting.
Can we convert a certain Data Type to any other Data Type?
- There are certain limitations to it. Every time, it is not possible to convert data to any other data type. But python provides a lot of flexibility in their built-in Basic data types.
- We can easily convert int to float, and strings very easily.
- Python provides the built-in helper functions to do the conversion in a single line.
Also Read – Basic Data Types in Python 3 – Int, Complex, Float, Double and String
int() function – To convert data type to Integer
- This function takes one argument. It can be float, Bool, or String.
- We can’t convert complex number to int. Passing a complex number will result in an error.
- While passing a string literal, it is compulsory to pass it in a decimal base. Otherwise, it will result in a Value Error.
int(123.43)
int(True)
int("10")
# Below statements will result in value error.
int("ten")
int("10.2")
int("0A11")
float() function – To convert data type to Floating Point Number
- Similar to int() function, We can convert Integer, Bool, and String literals to float. But we can’t convert to float from a complex number.
float(50)
float(False)
float("10.2")
complex() function – To convert data type to Complex Number
- This is an overloaded function. So, we can either pass the real part or with the Real and imaginary part.
- Form 1 – complex(x) – Here x will be considered as the real part of your resultant complex number. The imaginary part will be 0 by default.
- Form 2 – complex(x, y) – Here x is the real part, and y is the imaginary part.
- We can convert int, Bool, float, and String literals to complex number using this function.
complex(10)
complex(10,2)
complex(True)
complex(True, True)
complex("120")
bool() function – To convert a data type to Boolean
- We can convert float, int, String, and complex number to Bool value using this function.
- For Integers and Float – Any non-zero value will be converted into True. Otherwise, it will be converted to False.
- For Complex Number – It will return False only when real and imaginary part of a complex numbers are 0. Otherwise, it will return True.
- For Strings – It will return True to any string value. It will return False when we pass empty string.
bool(20)
bool(0.0)
bool(1+1j)
bool("")
bool("ten")
str() function – To convert a data Type to Strings
There is no restriction in this function. It will return the string value to everything which is passed with the function.
str(10+6j)
str(True)
str(2)
str(2.0)
Last Words
I hope you will find this article on Type Coercion or Type Casting in Python useful. If you have any doubts or suggestions regarding the content then do comment below. I will reply to each and every query here.
Leave a Reply