Python TYPE CASTING (PYTHON FUNDAMENTALS)

Created with Sketch.

Python TYPE CASTING

֍ We can convert one type value to another type. This conversion is called Typecasting
       or Type coersion.
֍ The following are various inbuilt functions for type casting.
1) int()
2) float()
3) complex()
4) bool()
5) str()

֍ int():


We can use this function to convert values from other types to int

 >>> int(123.987) 
 123 
 >>> int(10+5j) 
 TypeError: can't convert complex to int 
 >>> int(True) 
 1 
 >>> int(False) 
 0 
 >>> int("10") 
 10 
 >>> int("10.5") 
 ValueError: invalid literal for int() with base 10: '10.5' 
 >>> int("ten") 
 ValueError: invalid literal for int() with base 10: 'ten' 
 >>> int("0B1111") 
 ValueError: invalid literal for int() with base 10: '0B1111' 

Note:
1) We can convert from any type to int except complex type.
2) If we want to convert str type to int type, compulsory str should contain only integral
value and should be specified in base-10.

֍ float():


We can use float() function to convert other type values to float type.

 >>> float(10) 
 10.0 
 >>> float(10+5j) 
 TypeError: can't convert complex to float 
 >>> float(True) 
 1.0 
 >>> float(False) 
 0.0 
 >>> float("10") 
 10.0 
 >>> float("10.5") 
 10.5 
 >>> float("ten") 
 ValueError: could not convert string to float: 'ten' 
 >>> float("0B1111") 
 ValueError: could not convert string to float: '0B1111' 

Note:
1) We can convert any type value to float type except complex type.
2) Whenever we are trying to convert str type to float type compulsory str should be
either integral or floating point literal and should be specified only in base-10.

֍ complex():


We can use complex() function to convert other types to complex type.
Form-1: complex(x)
We can use this function to convert x into complex number with real part x and imaginary
part 0.

 complex(10)==>10+0j 
 complex(10.5)===>10.5+0j 
 complex(True)==>1+0j 
 complex(False)==>0j 
 complex("10")==>10+0j 
 complex("10.5")==>10.5+0j 
 complex("ten") 
 ValueError: complex() arg is a malformed string

Form-2: complex(x,y)
We can use this method to convert x and y into complex number such that x will be real
part and y will be imaginary part.
Eg: complex(10, -2) –> 10-2j
complex(True, False) –> 1+0j

֍ bool():


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

1) bool(0) --> False 
2) bool(1) --> True 
3) bool(10) --> True 
4) bool(10.5) --> True 
5) bool(0.178) --> True 
6) bool(0.0) --> False 
7) bool(10-2j) --> True 
8) bool(0+1.5j) --> True 
9) bool(0+0j) --> False 
10) bool("True") --> True 
11) bool("False") --> True 
12) bool("") --> False

֍ str():


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

 >>> str(10) 
 '10' 
 >>> str(10.5) 
 '10.5' 
 >>> str(10+5j) 
 '(10+5j)' 
 >>> str(True) 
 'True'

Leave a Reply

Your email address will not be published. Required fields are marked *