Please enable JavaScript to use CodeHS

Casting in Python

Learn how to convert variables of one type into another.

By Evelyn Hunter

Casting

Casting is the process of converting the value of one type into the value of another. In some cases, methods or concatenations are only possible when a value is converted from one type to another.

For example, a programmer wants to print their mailing address to the console, but has stored their zip code in an int value:

zipcode = 11231
address = "23 State Street Brooklyn, NY"
print(address + zipcode)
Plain text

This program will result in a TypeError: must be str, not int because the values passed to the print statement must be of type str. In order to print the value of zipcode, zipcode will need to be converted into a str type value.

Luckily, converting primitive data types from one type to another is fairly simple in Python. To do so, the value simply needs to be passed through a constructor function:

str() - constructs a string value from the given data type
int() - constructs an int value from a float, or string value
float() - constructs a float value from an int or string value
Plain text

In order to get the previous program to work, the zipcode variable needs to be passed through the str() constructor function:

zipcode = 11231
address = "23 State Street Brooklyn, NY"
print(address + str(zipcode))
Plain text

str(zipcode) can also be stored in another variable and used later in the program:

zipcode = 11231
zipcode_string = str(zipcode)
address = "23 State Street Brooklyn, NY"
print(address + zipcode_string)
Plain text

While casting to a str will preserve the correct value of an int or a float, casting to an int or float may change the numerical value of the variable that is input into the constructor function.

For example, float values that are converted to int will drop the decimal values of the given float:

number = 14.6
print(int(number))    #prints the value 14
Plain text

Practice

Try to create the following print statement using casting and the variables provided in the example below:

I have 2 cats and 1 dog - 3 animals in total!
Plain text

Implicit Casting

Implicit casting is when Python automatically casts the value correctly without the programmer needing to do so. The most prevalent example of this is the automatic conversion of an int to a float when a float and int are combined in a mathematical operation:

num1 = 6
num2 = 5.7
num3 = num1 + num2
print(num3)  #prints the value 11.7
print(type(num3)) # prints <float>
Plain text

The value of num3 is automatically converted to a type float during the mathematical operation.