4 Boolean, Sequence, and Mapping Classes
4.1Lesson goals¶
Perform logic testing with the
boolclass.Create simple sequences of objects with the
list,tuple, andrangeclasses.Associate keywords to values using the
dictclass.Learn how initialize variables.
Utilize the
Noneclass to create a controlled starting values for variables.
4.2Overview¶
In a previous lesson we learned how to send simple commands to the Python shell and create numeric- and text-based data classes. In this lesson, we will explore some other useful data classes including logic, sequence, and mapping classes. Finally, we will end with a quick discussion on how to initialize a variable without assigning a value to it.
4.3Logic class: booleans (bool)¶
In addition to numbers and text, Python also handles boolean / logic
testing using the bool class.. There are only
two values for the bool class: True and False. We can define a bool object by assigning a variable either
the True or False value. The block of code below first creates two bool objects and then checks their data
class using the type() function (see the previous lesson regarding numbers and text for details on
this function):
a = True
b = False
print(type(a))
print(type(b))<class 'bool'>
<class 'bool'>
The bool class is very useful when used in conjunction with Python’s various comparison and boolean operators. There
are eight built-in comparison operators for Python.
These operators are listed in the table below:
| Comparison Symbol | Meaning |
|---|---|
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
== | Equal |
!= | Not equal |
is | object identity |
is not | negated object identity |
We can compare objects using these operators and bool objects. Two comparisons between three different float
objects is shown below:
a = 25.6
b = 37.5
c = 52.6
print(a < b)
print(a >= c)True
False
Furthermore, Python has three built-in boolean operators, which are listed in the following table:
| Boolean Symbol | Meaning |
|---|---|
x or y | Either x or y must be true for True, else False |
x and y | Both x and y must true for True, else False |
not y | If y is false, then True, else False (flip bool value) |
The boolean operators and and or are often used to chain multiple comparisons together. Below is a chained
comparison example that uses the and operator:
a = 25.6
b = 37.5
c = 52.6
print((b > a) and (c > a))True
Since both statements are True, this makes the entire evaluation True.
Interestingly, the bool objects True and False act like the integers 1 and 0, respectively. To see
this, see the following comparison operations:
d = True
e = False
print(d == 1)
print(e == 0)True
True
In both cases we get a True output. This feature is sometimes used when doing simple logical mathematical
operations.
4.3.1Example: A voltage check¶
A resistor is a fundamental electrical circuit component designed to dissipate electrical energy. The amount of “resistance” a resistor has in an electrical circuit is described with Ohm’s law, which is,
where is the electrical voltage (units: voltage, ) across the resistor and is related to a change in electrical energy, is the electrical current applied to the circuit (units: ampere / amp, ), and is the resistance (units: ohm, ).
A resistor has of electrical current passing through it. Prove that the voltage across the resistor is less than the maximum voltage that this resistor can handle.
Solution:
We first need to calculate the voltage across the resistor based on the provided current and resistance. Then
we can create a bool object that compares the calculated voltage to the maximum voltage the resistor can handle.
We use the print() function to display the bool object’s value to prove it is smaller than . Details
on how to do this is shown below:
current = 0.5
resistance = 2.5
voltage_max = 10
voltage = current * resistance
test = voltage < voltage_max
print(voltage)
print(test)1.25
True
The True output confirms that the calculated voltage is less than the maximum value
(i.e., ).
4.4Sequence classes: lists, tuples, and ranges¶
So far, we have handled data as discrete values, but sometimes it is useful to organize data within a common framework
(i.e., a sequence, an ordered representation of multiple values). You have already seen a sequence class with the str class since it is
just a sequence of text-based characters. We will revisit this concept in an upcoming lesson. However,
there are three other types of
built-in sequence classes that you will often encounter in Python.
4.4.1Lists (list)¶
A list (list)
is a mutable sequence of objects (i.e., can be changed after creation).
Lists are allowed to store mixed classes. You can have an all int-based list object or a list that can
contain int, float, str, and other classes. Creating a list is straightforward; all it requires is that a sequence of data is bounded between squared brackets ([ ]) and are separated with commas (,). Below is an example
of creating a simple four-unit, all int-based list.
x = [1, 2, 5, 8]
print(x)[1, 2, 5, 8]
Once a list is created, it can be searched and modified. There are a few built-in functions and operations for list
objects that allow for this. For example, we can extract an individual value in a list by calling its index
position via the operation:
print(x[2])5
Here the value in the 2nd indexed position of x (i.e., 5) is printed out to the terminal.
Python, like many other programming languages, defines the first index position in a sequence as position 0. You can see this in the following code:
print(x[0])1
Since a list is mutable, we can modify its contents. This done using the command:
list[index] = valueThe code block below changes our previous x object’s third value (index position 2) from 5 to 10.
print(x)
x[2] = 10
print(x)[1, 2, 5, 8]
[1, 2, 10, 8]
Furthermore, we can extract a portion of a list by add the colon symbol (:) to our indexing operation:
print(x)
z = x[1:4]
print(z)[1, 2, 10, 8]
[2, 10, 8]
Note the “exclusive nature” of the end point 4, it does not include the 4th position in x (does not even exist).
Here the code structure,
x[start_index:end_index]Has start index being inclusive and end index being exclusive.
The built-in list() function can also be used to
create list objects:
seq = list((1, 2, 3, 4))
phrase = list("hello")
print(seq)
print(phrase)[1, 2, 3, 4]
['h', 'e', 'l', 'l', 'o']
There are many other operations and functions that are built into the list class, including finding a maximum and
minimum value, determining the number of entries in a list (i.e., the “length” of a list, shown in the next section),
and more. It is highly recommended to visit the
official Python documentation page on sequence classes
if you are interested in exploring more functionality.
4.4.1.1Example: A list full of lengths¶
Create a list of floating point numbers that contains the following for length measurements:
, , , and
Then, convert each one of these values individually from centimeters to inches (recall that ), and print out each of the converted values. Finally, create a new list that contains these converted values and print out the entire list at once.
Solution:
This example reviews how to create list objects and how to extract individual values from the list. First, we
create a list called lengths_in that contain all the provided lengths (with units of inches). We then extract
each value using the appropriate index value (remember in Python that the first index position is 0!). Finally,
we create a new list called lengths_cm that contains the converted lengths. See the block of code below that goes
over all these steps:
lengths_in = [0.2, 0.5, 0.3, 2.5]
print(lengths_in[0] * 2.54)
print(lengths_in[1] * 2.54)
print(lengths_in[2] * 2.54)
print(lengths_in[3] * 2.54)
lengths_cm = [(lengths_in[0] * 2.54), (lengths_in[1] * 2.54),
(lengths_in[2] * 2.54), (lengths_in[3] * 2.54)]
print(lengths_cm)0.508
1.27
0.762
6.35
[0.508, 1.27, 0.762, 6.35]
While the example above does get the job done, there are more efficient ways of doing this using looping statements or the NumPy library. We will explore both concepts in later lessons!
4.4.1.2The len() function¶
The function len() is often used to report the number of
items (i.e., objects) in a list. This useful function can also be with other as well many other sequence-based
classes, but for our purposes now let’s focus on using it with list objects. There are many programming
situations in which knowing the length of a list is important, such as performing iterative operations using
for loops andif statements. Examples of these operations will be described in a later lesson,
but for now, let’s practice using the len() function.
Shown below are the two lists x and y that we created in the last section. Let’s call len() on each object:
x = [1, 2, 5, 8]
y = list("germanium")
print(len(x))
print(len(y))4
9
As seen in the output, the length of x and y are 4 and 5, respectively. This makes sense as there are four
integers in x and the word “hello” consists of five characters.
4.4.1.3Lists and strings: setup matters!¶
Creating a list out of a string or set of strings can lead to unexpected results if you are not careful in how
you initialize your list. Python provides a few simple ways to create a string-based list object. The code below
goes over three different methods:
phrase = ["Silicon Dioxide"]
words = ["Silicon", " ", "Dioxide"]
letters = list("Silicon Dioxide")
print(phrase)
print(words)
print(letters)['Silicon Dioxide']
['Silicon', ' ', 'Dioxide']
['S', 'i', 'l', 'i', 'c', 'o', 'n', ' ', 'D', 'i', 'o', 'x', 'i', 'd', 'e']
The first print statement displays a one item list that contains the phrase Silicon Dioxide. The second
example shows a list with the phrase Silicon Dioxide broken up into three parts: Silicon, <the space character>, and Dioxide, with the middle entry being the “space” character. The third example creates a list using the
individual letters of Silicon Dioxide via the list()
function.
All three options are commonly used so be aware of your intent when creating a string-based list to prevent unexpected behavior!
4.4.2Class preservation of sequenced objects¶
A subtle, but important, aspect of sequenced classes (like lists) is that objects residing in these sequenced
classes retain their original class designation. For example, if an int object resides in a list, this int
object is still identified as an integer and retains all the features and limitations of that object. To see this
behavior in action, let’s look at the following list called data and check its data type:
data = [1, 2.2, "contact angle"]
print(data)
print(type(data))[1, 2.2, 'contact angle']
<class 'list'>
In the above code block we can see that data is registered as a list, which is expected. Looking at data some
more we see that the first object should be an int, followed by a float, and then finally a str. To confirm this
we run type() on each indexed object:
print(data[0])
print(type(data[0]))
print(data[1])
print(type(data[1]))
print(data[2])
print(type(data[2]))1
<class 'int'>
2.2
<class 'float'>
contact angle
<class 'str'>
Sure enough, we get the expected classes for each sequenced object. Therefore, objects inside of sequence classes, like lists, still retain their intrinsic class.
4.4.3Nested lists¶
We can even create list objects out of list objects! This is called
nesting, and has some interesting ramifications in terms of data storage and numerical analysis (e.g., creation of matrices).
Creating a nested list is no different from creating a list with other classes. We simply follow the same setup as
creating a list out of int, float, or str objects, but instead insert list objects:
n = [[1, 2], [3, 4], [5, 6]]
print(n)
print(type(n))[[1, 2], [3, 4], [5, 6]]
<class 'list'>
The block of code above creates a two-level, nested list structure called n. Here you can see that each entry in the
top-level “list” structure contains “sub-lists” separated by the , character. Python still registers this object as a
list.
Indexing of a nested list works the same way. For instance, let’s call the first entry in n:
print(n[0])
print(type(n[0]))[1, 2]
<class 'list'>
Notice here that the first entry in n is [1, 2] and NOT 1. This is because we called the first sequenced
object, which is the list [1, 2]. The data type for this entry is also a list, which should be expected by now.
To call an object inside one of these sub-lists, we tack on an additional indexing operator. For example, if
we wanted to get the value of the second object in this first sub-list (here the value 2) we would issue the command:
print(n[0][1])2
Again, we follow the nomenclature that the first indexed position is the 0th position in Python. Using this setup we can also perform other operations on individual objects in a nested list like below:
n = [[1, 2], [3, 4], [5, 6]]
print(n)
print(n[2][0])
print(type(n[2][0]))
n[2][0] = 13.1
print(n)
print(n[2][0])
print(type(n[2][0]))[[1, 2], [3, 4], [5, 6]]
5
<class 'int'>
[[1, 2], [3, 4], [13.1, 6]]
13.1
<class 'float'>
In this example, we call the first object in the third list (5) and check its data type. Then we change its value
to 13.1, check its new data type, and then finally display n after its modification. All in all, utilizing
nested lists is no different from a simple list once you understand how to properly index all positions in the object.
4.4.3.1Example: Nesting operations¶
Create a nested list called dataSet that has the following structure:
[1.2, 5.5, 7.6], [2.5, 6.5, 0.2], [3.2, 3.0, 8.8]]
Next, have the interactive shell display the values 5.5, 2.5, and 8.8 from the nested list one at a time.
Finally, set the second position of each sub-lists’ value to 10 and print out the now modified nested list.
Solution:
This example has you practice indexing nested lists. Remember that the first index position after the variable name represents the sub-list’s position in the overall list, and the second index position represents the value in that sub-list.
The first step is to actually create the list:
dataSet = [[1.2, 5.5, 7.6], [2.5, 6.5, 0.2], [3.2, 3.0, 8.8]]Now, let’s print out to the console the three required values (remember that index positions start at 0!):
print(dataSet[0][1])
print(dataSet[1][0])
print(dataSet[2][2])5.5
2.5
8.8
Finally, let’s modify the second position in each sub-list and print out the now modified dataSet:
dataSet[0][1] = 10
dataSet[1][1] = 10
dataSet[2][1] = 10
print(dataSet)[[1.2, 10, 7.6], [2.5, 10, 0.2], [3.2, 10, 8.8]]
4.4.4Representing matrices with lists¶
Readers who have taken a linear algebra course may wonder if lists can be used to represent matrices. The short answer is yes, in theory, but as we will show soon, there are some limitations and workarounds that are required to successfully implement lists in this way. Even with these limitations, the ability to represent matrices as lists does open the prospect of using Python in numerical method applications like transformation operations, differential equation analysis, quantum mechanic calculations, and much more!
While understanding the details of matrix operations is beyond the scope of this guide, a matrix can be thought of as a tabulated data array of values (e.g., numeric, symbolic, expressions). Each tabulated value is sometimes referred to as a “cell”, and its position in a matrix is given via a coordinate system following the “row, column” format (e.g., “row 5, column 2”).
Knowing this, one can make the logical leap to represent matrices using lists. For example, a one-dimensional matrix
(sometimes referred to as a vector) can be represented using
a list. A two-dimensional matrix can be represented with a two-level nested list (similar to what is shown in the
last section). Here the first indexed position after the variable name represents the row number in
the matrix and the second indexed position represents the column number. The only mapping that needs to be done is
to translate Python’s starting indexing value of 0 to a matrix’s starting index value of 1.
To see this in action, let’s try to create the following 3 x 2 matrix in Python:
If we assume a two-level nested list structure, each sub-list represents a row entry and the position in each sub-list represent the column position. Following what we now know about nested-lists, we can create a representation of this matrix in Python and call individual cells with the following commands:
a = [[1, 2], [3, 4], [5, 6]]
print(a)
print(a[1])
print(a[2][1])[[1, 2], [3, 4], [5, 6]]
[3, 4]
6
Here our first print command displays the entire matrix, the second print command shows the second row, and the third print command retrieves the cell in the third row, second column position.
However, we soon run into some fundamental issues when treating lists as matrices. One simple example of this is in the addition of two matrices. Matrix addition is a cell-by-cell operation across two matrices that have the same dimensions. For a set of 3 x 2 matrices, this can be symbolically represented as:
and simple numerical example is shown below for completeness:
Let’s see what happens if we re-create these two matrices in Python and add them together using the + operator:
a = [[1, 2], [3, 4], [5, 6]]
b = [[0, 3], [5, 7], [2, 1]]
c = a + b
print(c)[[1, 2], [3, 4], [5, 6], [0, 3], [5, 7], [2, 1]]
Unfortunately we don’t get the expected results. Rather, Python created a new nested list that simply appended the
second list b to the end of our first list a. This example reinforces the fact that in Python the object class
list is a special sequence class and not a one-to-one representation of a matrix. Even with this negative result, we
can see that fundamentally Python should be able to handle matrices, but we need to be more knowledgeable in Python to
make this work. Don’t worry, as we will see in later lessons that both looping statements
or the NumPy library can be utilized to achieve this!
4.4.5Tuples (tuple)¶
The tuple class (tuple)
is similar to the list class, except that it is immutable (i.e., it
cannot be altered once created). Tuples are useful when you want a sequence of data that cannot be changed after
creation.
The word “tuple” is often said two different ways phonetically (both are correct):
“Tuh-puhl”
“Too-puhl”
Creating a tuple is similar to creating a list, except you use parentheses symbols (( )). Below are two
examples of how to create tuple objects:
m = (1, 2, 5, 8)
n = tuple("hello")
print(m)
print(n)(1, 2, 5, 8)
('h', 'e', 'l', 'l', 'o')
tuple objects are indexed the same way as list objects:
key = (1, 3, 5, 7, 9, 100)
print(key[1])
print(key[2:5])3
(5, 7, 9)
For a new user, the biggest difference to remember about a tuple compared to a list is its immutability. We cannot
change a value in a tuple once it is created. If we run the following code, the Python shell will output an error:
key[1] = 2.4
print(key)---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[28], line 1
----> 1 key[1] = 2.4
2 print(key)
TypeError: 'tuple' object does not support item assignmentReading the TypeError line above confirms that values in a tuple cannot be reassigned.
4.4.6Ranges (range)¶
The range class (range) at first seems like an odd sequence class as it does not directly describe a
sequence with stored values. Rather it is used in the construction of a sequence.
A common use of the range class is in the creation of list and tuple objects. The
range class has one required input, the stop value which
marks the end of a sequence. The code below constructs a list object using the range class.
a = list(range(5))
print(a)[0, 1, 2, 3, 4]
Here the range object with a stop value of 5 is passed through the list() function to create a list of integers
between 0 through 4. The starting value is 0 and the final value is 4, which means that the stop value of 5 is
exclusive.
While the range class only requires a stop value input argument, it can also accept a starting value and
stepping value in the format:
range(start, stop, step)Therefore, we can easily create lists and tuples of varying
size and step without directly typing in each value! Below are a few examples on on how the range class can be used
when creating list objects:
b = list(range(10))
c = list(range(1, 10))
d = list(range(1, 10, 2))
print(b)
print(c)
print(d)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
Each subsequently created list uses a more complex calling of the range class. By default, if only one value is
entered as an input (i.e., object b in the example above), the Python interpreter treats this as the stop value and
will iterate from 0 up to one less than stop in integer steps of one. Adding a , symbol tells the Python shell
that the first value is start and the second value is stop (i.e., object c in the above example). Finally,
object d is the fully written out version of the range class in which the last of the three values is step.
As you can imagine, we can even create sequences in reverse order by using a negative step value. The code block below
demonstrates this:
e = list(range(10, 1, -2))
f = list(range(10, -5, -2))
print(e)
print(f)[10, 8, 6, 4, 2]
[10, 8, 6, 4, 2, 0, -2, -4]
There are limits though to what we can do. Below is an example of start being less than stop while also using a negative
step:
g = list(range(1, 10, -2))
print(g)[]
Here, the shell already thinks the list is done and nothing is populated. Furthermore, the range class only
accepts int inputs, so if you tried to run the following code below, the shell will produce the following error:
badList = list(range(5.2, 25.3, 2.2))
print(badList)---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[33], line 1
----> 1 badList = list(range(5.2, 25.3, 2.2))
2 print(badList)
TypeError: 'float' object cannot be interpreted as an integerSo there are limits to what we can do with the built-in Python sequence classes, but hopefully you can see the
possible usefulness of using these sequence classes in storing multiple data values or using them as representations of
mathematical arrays. Creating multi-dimensional, sequence-based objects using the built-in list,
tuple, or range classes is unfortunately cumbersome at times. Thankfully, the Python language has a very elegant and powerful add-on library called NumPy that elegantly handles this need. We will introduce NumPy in a later lesson after we become more familiar with Python.
4.4.6.1Example: A range of numbers¶
Create a list that spans from -10 to 40 with a step size of 4 using the range. Next, repeat this
range but increase the step size to 7. Print out both lists to the terminal.
Solution:
First, let’s construct our list that has a step size of 4:
step_four = list(range(-10, 40, 4))
print(step_four)[-10, -6, -2, 2, 6, 10, 14, 18, 22, 26, 30, 34, 38]
First, now we repeat but with a step size of 7:
step_seven = list(range(-10, 40, 7))
print(step_seven)[-10, -3, 4, 11, 18, 25, 32, 39]
4.5Mapping classes: dictionaries (dict)¶
Mapping classes allow us to translate a “keyword” (i.e., a “key”) into something else. For example, simple digital circuits will often have only two output states: a “high” state and the “low” state. In terms of logic analysis, this is often represented by the integer values “1” and “0”, respectively. So,
key:
high→ value:1key:
low→ value:0
Dictionaries
(dict) allow for this
key to value mapping. In its simplest form, a dict object is a mapping of a single key to a single value. For
example, let us create an object called ridge who has a mapped height of 20.5:
ridge = {"height" : 20.5}Notice how a dict object is created, we encompass the key and value around curly bracket symbols ({ })
and use the colon symbol (:) via the general form:
dict_object = {key : value}If we want to ever recall the height value for ridge, we would run the following code:
print(ridge["height"])20.5
Notice how this looks similar to recalling a value in a list or tuple but now we use the key instead of an
indexing position. We can also reassign the value of height by running the following code:
ridge["height"] = 31.5
print(ridge["height"])31.5
Dictionaries can also contain multiple mappings to increase their functionality. For example, let’s create a dictionary that maps multiple features of a measured sample and then recalls them (we will ignore units to keep the example simple):
silicon = {
"type" : "semiconductor",
"meltPoint" : 1687,
"resistivity" : 5.23,
"inorganic" : True
}Here we have mapped four values (a str, an int, a float, and a bool) to four keys. Each mapping is separated by
a comma. This is how the Python shell knows there are multiple mappings. Furthermore, notice that in the above example
each mapping is entered as a new line. This is done for readability purposes. We could have entered all the mappings
using an in-line input format, but it would have been harder to read.
We can then recall any value we wish by using the appropriate key:
print(silicon["type"])
print(silicon["meltPoint"])
print(silicon["resistivity"])
print(silicon["inorganic"])semiconductor
1687
5.23
True
There are also special, built-in functions specifically for the dict class. This type of special function that works
directly on an object is called a method, and are an extremely important
feature of object-oriented programming (OOP).
While we will go into more detail about methods in a future lesson, for now let us try out some simple methods for the dict class. For example, the .items() method will list out all keyword : value mappings for an object. To call a
method associate with an object we use the following command structure:
object.method()
Let’s try this with the .items() method:
For example, the dict method .items() will list out
all key : value mappings for an object. Let’s issue this command on silicon object:
print(silicon.items())dict_items([('type', 'semiconductor'), ('meltPoint', 1687), ('resistivity', 5.23), ('inorganic', True)])
While you should be familiar with the print() function by now, notice how the .items() method is implemented
with silicon. The notation here is probably different from what you may have expected. Possibly you thought it was
going to be items(silicon)? The notation silicon.items() implies that .items() is a function associated with the
object silicon (i.e., a dict object); therefore it is a method.
Two other useful methods for the dict class we can go over right now are
.keys() and
.values(), which provide an ordered sequence of the
keys and mapped values, respectively:
print(silicon.keys())
print(silicon.values())dict_keys(['type', 'meltPoint', 'resistivity', 'inorganic'])
dict_values(['semiconductor', 1687, 5.23, True])
What is nice about dict objects is that they provide a way to link a human readable concept (e.g., “height”,
“resistivity”, etc.) to a value rather than memorizing index numbers. Furthermore, dictionaries are also a starting
point step to object-oriented programming.
4.5.1Example: A dictionary for gases¶
You are tasked to create a digital library that stores important material properties of common gasses. Store the
following important material properties about argon in a dict object, and then print out the keys and values of the
object using the .keys() and .values() methods. Finally, print out just the molecular weight of argon with a
separate print() command.
Name: Argon
Atomic number: 18
Molecular weight: 39.95 g/mol
Melting point: -189.3 °C
Boiling point: -185.8 °C
Note: Do not worry about storing each value’s unit in the dictionary.
Solution:
First, let’s follow the lesson notes above to create our dict object (remember to include the ,
between each mapping!) and then use the two methods to recall both the keys and values. Finally, we recall the
molecular weight by indexing with the molecular_weight key.
argon = {
"name" : "argon",
"atomic_number" : 18,
"molecular_weight" : 39.95,
"melting_point" : -189.3,
"boling_point" : -185.5
}
print(argon.keys())
print(argon.values())
print(argon["molecular_weight"])dict_keys(['name', 'atomic_number', 'molecular_weight', 'melting_point', 'boling_point'])
dict_values(['argon', 18, 39.95, -189.3, -185.5])
39.95
4.6Initializing variables¶
As seen in the examples so far, the Python interpreter automatically tries to assign class to a created object based on what is entered in the shell prompt. Not all languages can do this, and for those languages one has to explicitly state the class when creating an object. Sometimes though it is useful in Python to assign a variable to a class without providing a value(s). This is straightforward for simple data classes by using their built-in class initialization commands:
integer = int()
floating = float()
string = str()
boolean = bool()
print(type(integer))
print(type(floating))
print(type(string))
print(type(boolean))<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
As you can see, we get the appropriate classes. But what about the actual value assigned to the variable?
print(integer)
print(floating)
print(string)
print(boolean)0
0.0
False
Notice the default states for the four classes issued above:
int→0float→0.0str→ “void character”bool→False
Sequenced objects are a bit harder to do, but can be done. Below is a way to initialize a list object. The actual
command looks a bit confusing at first:
# Create a list object of length five with zeroes
list_obj = [0] * 5
print(list_obj)[0, 0, 0, 0, 0]
Here we initialized the list object by taking a starting a starting list object [0] and multiplying it by 5. At
first glace one may think you should just get [0] as it looks like you are multiplying a mathematical array, but
remember that lists are not mathematical arrays, they do not follow matrix math rules.
4.6.1Safe initialization using None¶
The constant None is a bit of an odd duck in Python. It is designed to represent an absence of a value or null state.
Issuing None to a variable creates an object of the NoneType class.
a = None
print(type(a))
print(a)<class 'NoneType'>
None
The None state is NOT the same as 0 or False, it is distinctly different from the mapping of 0 →
False. For example, let’s compare a None to 0 and False:
a = None
print(a == 0)
print(a == False)
print(False == 0)False
False
True
Issuing None to a variable creates an object of the NoneType class. If we later change the value assigned to the
variable we will also change it’s class away from NoneType:
a = None
print(type(a))
print(a)
a = 23.6
print(type(a))
print(a)<class 'NoneType'>
None
<class 'float'>
23.6
This behavior is very useful in scenarios when we want to initially create a variable but not want to provide a meaningful value to it. At some point later we can then add the correct value to it. This allows us to create code that can initialize objects that do NOT have their initial values associated with a number or text value.
While the use of None may not be fully apparent right now, it will become extremely useful when learn about
conditional statements and functions.
4.7Final thoughts¶
The first lesson and this lesson have introduced some basic, but important data classes that are
useful for an engineer learning the fundamentals of Python. However, there are many more classes out there as you dive
deeper into Python, and there is still a lot to learn even with these basic classes and functions. For example, we
currently have shown how the print() function is used to display output from the Python shell. We have primarily used
it to display multiple lines of output. Our current way is still pretty cumbersome as we only can display one piece of
data per each print() command. Fortunately, there are numerous ways to increase the usefulness of the print()
output, but this requires us to explore the str class some more. That is for
another lesson though. As of now, congratulations on dipping your coding toes further
into Python!