Additional Data Type Topics¶
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.
Static vs. Dynamic Typing¶
In many programming languages, you specify a type for a variable upon creation. In those languages, you can change the value of the variable, but the new value must be consistent with the specified type of the variable. Languages with this property are referred to as being statically typed.
Python is a dynamically typed language. In such a language, we do not specify the type of a variable when we create it. We specify only a value, and Python infers the data type from that value. If we change the value of the variable in a way that is inconsistent with the current type of the variable, then Python simply changes the variable’s type.
Dynamic typing is demonstrated in the two cells below.
p = 4
print(type(p))
p = 3.999
print(type(p))
<class 'int'>
<class 'float'>
q = 7
print(type(q))
q = 7 / 1
print(type(q))
<class 'int'>
<class 'float'>
The None Type¶
Python provides a special value called None
that is used to indicate the absence of a value. In the cell below, we create a variable storing a value of None
. We then print this variable, as well as its type.
empty_var = None
print(empty_var)
print(type(empty_var))
None
<class 'NoneType'>
One situation in which you might encounter None
is if you attempt to assign to a variable the output (or return value) of a function that does not actually produce any output. The print()
function, for example, performs an action by displaying text to the screen, but does not actually return any values. We see this in the next cell, in which we attempt to store the output of print()
into a variable, and then print the value of this variable to confirm that is is None
.
my_output = print('Hello')
print(my_output)
Hello
None
We will discuss return values of functions and the None
value further in later lessons.