Type Casting Variables
We'll cover the following
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 = 5print(type(num_of_classes))num_of_classes = str(num_of_classes)print(type(num_of_classes))
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))
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 100python_popularity = int(python_popularity)print(python_popularity)