In this example, you will learn what is type casting and how type casting works in python with example.
There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.
The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion/casting. There are two types for type casting in python :
#implicit type casting num_int = 123 num_float = 1.23 print("datatype of num_int:",type(num_int)) print("datatype of num_flo:",type(num_float)) #explicit type casting str = "123" str_to_num = int(str) print("datatype of num_int:",type(str_to_num))
datatype of num_int: <class 'int'> datatype of num_flo: <class 'float'> datatype of num_int: <class 'int'>
Here in implicit type casting python will automatically define data type of variable while in explicit type program will force python to convert type of variable.
Ask anything about this examples