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!
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
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.