Converting of one type of data into another type is called as Type Casting or Type Conversion.
The inbuilt functions for type casting are :
- int()
- float()
- complex()
- bool()
- str()
- int():
This function is used to convert any type of data into int(integer type).
Examples:
1. >>>int(101.120)
Output: 101
2. >>>int(5+5j)
Output: TypeError: can’t convert complex to int
3. >>>int(True)
Output: 1
4. >>>int(False)
Output: 0
5. >>>int(“10”)
Output: 10
6. >>>int(“10.5”)
Output: ValueError: invalid literal for int() with base 10: ‘10.5’
7. >>>int(“ten”)
Output: ValueError: invalid literal for int() with base 10:’ten’
8. >>>int(“0B111)
Output: ValueError: invalid literal for int() with base 10: ‘0B111’ - float():
This function is used to convert any data type into float.
Examples:
1. >>>float(10)
Output: 10.0
2. >>>float(5+5j)
Output: TypeError: can’t convert complex to float
3. >>>float(True)
Output: 1.0
4. >>>float(False)
Output: 0.0
5. >>>float(“1”)
Output: 1.0
6. >>>float(“5.5”)
Output: 5.5
7. >>>float(“0B111”)
Output: ValueError: could not convert string to float: ‘0B111’ - complex():
This function is used to convert any data type into complex.
Examples:
1. >>>complex(10)
Output: 10+0j
2. >>>complex(10.5)
Output: 10.5+0j
3. >>>complex(True)
Output: 1+0j
4. >>>complex(False)
Output: 0+0j
5. >>>complex(“10”)
Output: 10+0j
6.>>>complex(“10.5”)
Output: 10.5+0j
7. >>>complex(“ten”)
Output: ValueError: complex()arg is a malformed string
Form-2:
complex(x,y): This is the another form to convert into complex number. With this method we can convert x and y into complex number such that x will be real part and y will be imaginary part.
Eg: complex(5,-5)
Output: 5-5j - bool():
This function is used to convert any data type into bool.
Example:
1. >>>bool(0)
Output: False
2. >>>bool(1)
Output: True
3. >>>bool(5)
Output: True
4.>>> bool(2.5)
Output: True
5. bool(0.12)
Output: True
6. >>>bool(0.0)
Output: False
7. >>>bool(10-5j)
Output: True
8. >>>bool(0.+2.5j)
Output: True
9.>>>bool(0+0j)
Output: False
10. >>>bool(“True”)
Output: True
11. >>>bool(“False”)
Output: True
12. >>>bool(“”)
Output: False - str():
This function is use to convert any datatype into str(string) type.
Examples:
1. >>>str(5)
Output: ‘5’
2. >>>str(5.5)
Output: ‘5.5’
3. >>>str(5+5j)
Output: ‘(5+5j)’
4. >>>str(True)
Output: ‘True’