python type casting example

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 :

  1. Implicit Type Casting : In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement.
  2. Explicit Type Casting :In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int(), float(), str(), etc to perform explicit type conversion.

Example :

    
#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))
   

Output :

    
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
datatype of num_int: <class 'int'>
    

Explanation :

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.


Share your thoughts

Ask anything about this examples