Python - Things to know before proceed - TypeCasting Tutorial
Type Casting is a method to convert one data type to another data type implicitly or explicitly.
Two types of Type Casting in Python are:-
- Implicit Type Casting
- Explicit Type Casting
Implicit Type Casting
In this process, python converts one data type to another data type automatically without the use of any function.
a = 1 # Integer Datatype
print(type(a))
b = 2.03 # Float Datatype
print(type(b))
c = a + b # Python automatically convert c into Float Datatype, as it is float addition
print(type(c))
print(c)
d = a * b # Python automatically convert c into Float Datatype, as it is float multiplication
print(type(d))
print(d)
Output:-
<class 'int'>
<class 'float'>
<class 'float'>
3.03
<class 'float'>
2.03
In the above program, the result data type of variables c and d is converted to float. Because python always converts smaller data types to larger data types to avoid the loss of data.
Explicit Type Casting
In this process, python converts one data type to another data type with the help of a function.
Some Type Casting functions are-
- int() :- int() function take float or String as an argument and return int type object.
- float() :- float() function take Int or String as an argument and return float type object.
- str() :- str() function take Int or float as an argument and return string type object.
- bool() :- bool() function take any value as an argument and return boolean (True or False) object. If the argument is None, False, Empty sequence, or 0 then it will return False, otherwise True.
- list() :- list() function take any value of different data type(string,int, float) as an argument and return List Object.
- complex():- It will return a complex number when a real and imaginary number is passed as an argument.
- tuple() :- tuple() function is used to create a tuple from any argument(list,dictionary, etc)
Example:-
a = 25.234 # Float Datatype
i = int(a)
print(i)
print(type(i))
b = 32 # Integer Datatype
f = float(b)
print(f)
print(type(f))
c = 32.267
s = str(a)
print(s)
print(type(s))
print(bool(False))
print(bool(0))
print(bool())
print(bool(None))
print(bool(True))
print(bool(2))
d = "Fresherbell"
l = list(d)
print(l)
print(type(l))
e = complex(3,7)
print(e)
print(type(e))
list1 = [1, 3, 'a', 'b', 3.14]
t = tuple(list1)
print(t)
print(type(t))
Output:-
25
<class 'int'>
32.0
<class 'float'>
25.234
<class 'str'>
False
False
False
False
True
True
['F', 'r', 'e', 's', 'h', 'e', 'r', 'b', 'e', 'l', 'l']
<class 'list'>
(3+7j)
<class 'complex'>
(1, 3, 'a', 'b', 3.14)
<class 'tuple'>