Type casting or Type conversion in Python allows casting or conversion of one value into another. At large, type casting or conversion is divided into two parts:
- Implicit Type Casting/Conversion
- Explicit Type Casting/Conversion
Let’s explore each type of casting in detail.
Implicit Type Casting/Conversion
Implicit type casting or conversion is done by Python Interpreter. Some key points to keep in mind about implicit type casting or conversion are:
- Casting or Conversion of type is done by Python Interpreter automatically
- Python Interpreter will only do implicit conversion or casting when there is no loss of data
- Python Interpreter will only do implicit conversion or casting when both the types involved are compatible for casting.
Let’s take a look at a few examples of implicit type conversion or casting. In the example below, we have two variables one of type integer and another of type float. Float is considered to be a higher data type as it allows more range of values compared to an integer type. Hence when we try to add two numbers, each one of being type float and integer, the resulting number is always of higher data type - in this case float. This is the case so that there is no loss of data or information as integer values can still be accommodated into float types.
Note: we are using
type() method to check the data type of a given variable
In this case, both variables involved were numbers and implicit type casting was possible. However, sometimes there is a need to explicitly cast values between incompatible data types like strings and numbers. Python Interpreter cannot implicitly convert values and will throw an error as shown below.
In that case, we use explicit type conversion or casting.
Explicit Type Casting/Conversion
Explicit casting is useful when Python Interpreter cannot implicitly convert between types for e.g. strings to numbers. In this we use built-in casting methods like
float(), str()`, etc. to convert one type to another.
In the example below, first we explicitly cast stringified number into float using
float() and then add the numbers.
Kick-Start Your Data Career
We offer a wide variety of programs and courses built on adaptive curriculum and led by leading industry experts.
- Work on projects in a collaborative setting
- Take advantage of our flexible plans and scholarships
- Get access to VIP events and workshops
The Python certificate course provides individuals with fundamental Python programming skills to effectively work with data.
Taught by data professionals working in the industry, the part-time Data Science course is built on a project-based learning model, which allows students to use data analysis, modeling, Python programming, and more to solve real analytical problems.
The Data Science bootcamp is an intensive course designed to launch students' careers in data.
The part-time Data Analytics course was designed to introduce students to the fundamentals of data analysis.