Python is a high-level programming language that provides functionalities for a number of operations.
To ensure consistency in the program, variable types may have to be specified sometimes. This is achieved through casting. As Python is an object-oriented language, classes can be used to define data types.
The three constructor functions used to cast python variables are
int()
: An integer variable constructed from an integer variable, a float variable, or a string variable.
float()
: A float variable constructed from an integer variable, a float variable, or a string variable.
str()
: A string variable constructed from an integer variable, a float variable, or a string variable.
Let’s look at a working example of type casting:
#integer castinga = int(4.00)b = int("67")c = int(4)print ('int(4.00) = ',a)print ('int("67") = ',b)print ('int(4) = ',c)print('\n')#float castingd = float(6.45)e = float("67.2")f = float(5)print ('float(6.45) = ',d)print ('float("67.2") = ',e)print ('float(5) = ',f)print('\n')#string castingg = str(4.00)h = str("67")i = str(4+6)print ('str(4.00) = ',g)print ('str("67") = ',h)print ('str(7) = ',i)