What is typecasting?

In simple terms typecasting is used to convert one data type into another, usually from string to integer type or float data type.

An example is when you need an user input in a specific data type like integer, you can use the int() function to accept input directly in integer data type.

Functions for typecasting :-

  • int() – To convert to integer.
  • float() – To convert to float.
  • str() – To convert to string.

Example Code :

Here are some code snippets that might help you to understand and implement the syntax.

1. Converting to integer

num = int(120.53)
print (num)

Output :

2. Converting to float

flt = float(102)
print (flt, type(flt))

Output :

The type() function

The type function returns the data type of the variable which is passed as an argument in the function. It comes really handy to understand data types in python.

As you can see from the above example the type() function is called in the print statement to return the class of the data type which the variable belongs to.

Hence, the function returned the class as float.

Please follow and like us:

Leave a Reply