Type Coercion¶
There are occasions when we would like to convert a variable from one data type to another. This is referred to as type coercion. We can coerce a variable to another date type by passing it to a function whose name is identical to the desired data type. For instance, if we want to convert a variable x
to an integer, we would use the command int(x)
. If we want to convert a variable y
to a float, we would wuse float(y)
.
We will study coercion more later, but for now, let’s see what happens when we coerce ints to floats and vice-versa.
# Coercing an int to a float.
x_int = 19
x_float = float(x_int)
print(x_float)
print(type(x_float))
19.0
<class 'float'>
# Coercing a float to an int.
y_float = 6.8
y_int = int(y_float)
print(y_int)
print(type(y_int))
6
<class 'int'>
Notice that we we coerce a float
to an int
, the Python does not round the float to the nearest integer. Instead, it truncates (or chops off) the decimal portion of the number. In other words, when performing float-to-int coercion, Python will ALWAYS round the number DOWN to the next lowest integer, regardless of the value of the decimal portion.