Learn how to convert variables of one type into another.
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:
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:
In order to get the previous program to work, the zipcode
variable needs to be passed through the str()
constructor function:
str(zipcode)
can also be stored in another variable and used later in the program:
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
:
Try to create the following print statement using casting and the variables provided in the example below:
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:
The value of num3
is automatically converted to a type float
during the mathematical operation.