# 18.2. Checking Assumptions About Data Types¶

Unlike some other programming languages, the python interpreter does not enforce restrictions about the data types of objects that can be bound to particular variables. For example, in java, before assigning a value to a variable, the program would include a declaration of what type of value (integer, float, Boolean, etc.) that the variable is allowed to hold. The variable x in a python program can be bound to an integer at one point and to a list at some other point in the program execution.

That flexibility makes it easier to get started with programming in python. Sometimes, however, type checking could alert us that something has gone wrong in our program execution. If we are assuming at that x is a list, but it’s actually an integer, then at some point later in the program execution, there will probably be an error. We can add assert statements that will cause an error to be flagged sooner rather than later, which might make it a lot easier to debug.

In the code below, we explicitly state some natural assumptions about how truncated division might work in python. It turns out that the second asumption is wrong: 9.0//5 produces 2.0, a floating point value!

In the code below, lst is bound to a list object. In python, not all the elements of a list have to be of the same type. We can check that they all have the same type and get an error if they are not. Notice that with lst2, one of the assertions fails.

# 18.3. Checking Other Assumptions¶

We can also check other assumptions about the values of variables, in addition to their types. For example, we could check that a list has fewer than 10 items.