Casting in Python

In python, there are different data types. Each of these data types perform their respective functions and can be used in specific operations.

However, we can convert a variable from one data type to another and use it in any desired operation. This conversion is called Type Casting.

Common data types in python are int for integers, float for floating values, str for strings, etc.

If we define a variable in one data type, say a float and we want to cast from that data type to another one; we use the syntax as follows:

New_data_type(variable)

In code, it’s written as:

number = 12.4

int(number)

Hence casting from a float data type to an integer.

For instance:

Running a code as seen in the image below, we declare three variables in the integer data type, float and the string respectively.

Then we cast them from one type to the others.

Python runs these lines of code to produce the following output:

Which prints the casted values and their new data type.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store