7554425D-0054-440D-B95E-D2ABC13D62CD Created with sketchtool.
Your Saved Info Packages

View your saved Course or Program Packages containing pricing and detailed curriculum.

Speak with a Learning Advisor.

Have any questions? We'll call you.

Fill out the form below and a Learning Advisor will reach out at a time convenient for you.

Please pick a valid date and time between 9 AM and 8 PM eastern (Monday to Friday)

By clicking "Book a call," you accept our Terms and will also receive exclusive offers and updates about new courses, workshops and events.

Python Tutorial

Python Casting

Ready to start your career in Data? Find out more about BrainStation's Python Course

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 int(), 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.

Set Password

You already have an account with BrainStation, but you still need to set up a password.