Variables

Type Casting Variables

Explore how to perform type casting in Python by converting variables between types like integers and strings. Understand when conversions are valid and how to avoid errors with incompatible types.

Type casting

Type casting or casting refers to changing an object from one type to another. This is also done by simply saving the updated value to the variable where needed.

Changing an integer to a string

Let’s create a variable that originally stored a number and then change its type to a string.

num_of_classes = 5 print(type(num_of_classes)) num_of_classes = str(num_of_classes) print(type(num_of_classes))

Integer to string conversion in Python

Changing a string to an integer

Now let’s declare a string variable and then change its type to an integer.

python_popularity = '100' python_popularity = int(python_popularity) print(type(python_popularity))

String to integer conversion in Python

Incompatible types

However, if we tried to convert an incompatible variable, it would result in errors or an unexpected output. The following example results in an error since the string “hundred” does not represent an integer value unlike “100”.

python_popularity = 'hundred' # this will result in an error # to solve it replace hundred with 100 python_popularity = int(python_popularity) print(python_popularity)

Incompatible types in Python

On this page

    In This Module