3. Logic, Sequences, and Mapping Data Classes#

3.1. Lesson overview#

In the 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 classes, sequence classes, and mapping classes. Finally, we will end with a quick discussion on how to initialize a variable without assigning a value to it.

3.2. Logic 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 (from the official Python documentation):

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. These operators are listed in the following table (from the official Python documentation):

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:

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 actually 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.

3.2.1. Example: 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,

\[ V = IR \]

where \(V\) is the electrical voltage (units: voltage, V) across the resistor and is related to a change in electrical energy, \(I\) is the electrical current applied to the circuit (units: ampere / amp, A), and \(R\) is the resistance (units: ohm, \(\Omega\)).

A 5 \(\Omega\) resistor has 0.5 A of electrical current passing through it. Prove that the voltage across the resistor is less than the 10 V 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 can use the print() function to display the bool object’s value to prove it is smaller than 10 V. Details on how to do this in Python is 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., 1.25 V < 10 V).


3.3. Sequence classes: lists, tuples, and ranges#

So far, we have handled data as discrete values, but sometimes it is useful to organize our data in a sequence (i.e., an ordered representation of multiple values). We have already introduced one type of sequence class to you, the str class, since a str is just a sequence of text-based characters. We will revisit this concept in an upcoming lesson. However, there are other sequence-based classes that you will often encounter in Python.

3.3.1. Lists (list)#

A list (class code: list) is a mutable sequence of data. Here, mutable means we can change the values inside a list after creation. Lists usually have the same type of data for all values in the sequence (e.g., all int), but it is not strictly required. Creating a list is straightforward; all it requires is that a sequence of data is bounded between squared brackets ([ ]) and are separated with commas (,).

x = [1, 2, 5, 8]

print(x)
[1, 2, 5, 8]

Definition: mutable

Means “likely to change”. In the context of programming, an mutable object is an object whose value can (and most likely will) change.

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 an operation similar to calling its value:

x[2] = 10
print(x)
[1, 2, 10, 8]

Here, we have reassigned the 2nd indexed position of x to 10 and then redisplayed x to show the change. Furthermore, we can extract a portion of a list by add the colon symbol (:) to our indexing operation:

z = x[1:3]
print(z)
[2, 10]

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.

3.3.1.1. Example: A list full of lengths#

Create a list of floating point numbers that contains the following for length measurements:

0.2 in, 0.5 in, 0.3 in, and 2.5 in

Then, convert each one of these values individually from centimeters to inches (recall that 1 in = 2.54 cm), 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 loop statements or the NumPy library. We will explore both concepts in later lessons!


3.3.1.2. The 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("hello")

print(len(x))
print(len(y))
4
5

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.

3.3.1.3. Lists 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, , 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 methods are commonly used in creating list objects that contain strings. It really depends on your application, so be aware of your intent when creating a string-based list to prevent unexpected behavior!

3.3.1.4. Class 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 we notice 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.

3.3.1.5. Nested lists#

So far we have shown list objects that contain int, float, and str objects. It is possible to have more complicated objects sequenced in a list, including the list class itself! This “list of lists” is commonly referred to as “nested lists”, and has some interesting ramifications in terms of data storage and numerical analysis.

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:

print(n[2][0])
print(type(n[2][0]))
n[2][0] = 13.1
print(type(n[2][0]))
print(n)
5
<class 'int'>
<class 'float'>
[[1, 2], [3, 4], [13.1, 6]]

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.

3.3.1.6. Example: 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 console 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]]

3.3.1.7. Representing 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 object. 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:

\[\begin{split} \pmatrix{1 & 2 \\ 3 & 4 \\ 5 & 6} \end{split}\]

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:

\[\begin{split} \pmatrix{a_{11} & a_{12} \\ a_{21} & a_{22} \\ a_{31} & a_{32}} + \pmatrix{b_{11} & b_{12} \\ b_{21} & b_{22} \\ b_{31} & b_{32}} = \pmatrix{a_{11} + b_{11} & a_{12} + b_{12} \\ a_{21} + b_{21} & a_{22} + b_{22} \\ a_{31} + b_{31} & a_{32} + b_{32}} \end{split}\]

and simple numerical example is shown below for completeness:

\[\begin{split} \pmatrix{1 & 2 \\ 3 & 4 \\ 5 & 6} + \pmatrix{0 & 3 \\ 5 & 7 \\ 2 & 1} = \pmatrix{1 & 5 \\ 8 & 11 \\ 7 & 7} \end{split}\]

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!

3.3.2. Tuples (tuple)#

The tuple class (class code: 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. Creating a tuple is similar to creating a list, except that parentheses symbols (( )) are used instead of squared brackets. Below are 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')

Definition: mutable

Means “unlikely to change”. In the context of programming, an immutable object is an object whose value cannot be altered after creation.

Similar indexing operations can also be done with tuple objects:

print(m[2])
z = m[1:3]
print(z)
5
(2, 5)

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:

m[2] = 10
print(x)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [27], in <cell line: 1>()
----> 1 m[2] = 10
      2 print(x)

TypeError: 'tuple' object does not support item assignment

Reading the TypeError line above confirms that values in a tuple cannot be reassigned.

3.3.3. Ranges (range)#

The range class (class code: range) at first seems like an odd sequence class as it does not directly describe a sequence with stored values. Rather, the range class represents the construction of a sequence. Furthermore, even though range objects are immutable, they are often used to create mutable sequences like list objects. This may sound confusing at first, but seeing how range works will clarify its usefulness.

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 shell 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)
Input In [32], in <cell line: 1>()
----> 1 badList = list(range(5.2, 25.3, 2.2))
      2 print(badList)

TypeError: 'float' object cannot be interpreted as an integer

So there are limits to what we can do with the built-in Python sequence classes. However, as an engineer you can already see the usefulness of using these sequence classes in storing multiple data values or using them as representations of mathematical arrays. Unfortunately, creating multi-dimensional, sequence-based objects using the built-in list, tuple, or range classes is cumbersome. 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.

3.3.3.1. Example: A range of numbers#

Using the range class, Create a list that spans from -10 to 40 with a step size of 4. 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]

3.4. Mapping classes: dictionaries (dict)#

Sometimes it is useful to have a keyword that can be translated into something else. For example, a simple digital circuit 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 “0” and “1”, respectively. So there is a “mapping” between high \(\rightarrow\) 1 and low \(\rightarrow\) 0. Therefore our “key” (in this case high or low) is mapped to a value (0 or 1).

Python can handle this mapping between a key and a value using the dictionary class (class code: dict). 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}

Here the key is the str object height and the value is a float object of 20.5. Creating a dict object is similar to a list or tuple object, but we encompass the key and value around curly bracket symbols ({ }) and use the colon symbol (:) to map the key to the value. Notice that the order in the mapping is key : value, the key comes first then the value.

If we want to ever recall height value for ridge, we would run the following code:

print(ridge["height"])
20.5

Notice how this looks similar to recalling an indexed value in a list or tuple, but instead of an index number we use the key. We can also reassign the value of height by running the following code:

ridge["height"] = 31.5
print(ridge["height"])
31.5
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

Definition: method

A function that is associated with a specific class or object. Methods are often used to access or modify features of a class or object.

For example, the dict method .items() will list out all key : value mappings for an object. To run this on our silicon object from before, we would run the following code:

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 tied only to 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.

3.4.1. Example: 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 the values’ units 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

3.5. Initializing variables#

As seen in the examples so far, the Python shell automatically knows what class to assign an object to based on what is entered in the terminal. Therefore, Python knows how to initialize and assign an object in one step. Not all languages can do this, and for those languages one has to explicitly state the class when creating an object. Sometimes it is useful in Python to assign a variable to a class without providing a value(s). Below are examples of initializing an int variable, a float variable, a str variable, and a bool variable without providing values:

integer = int()
floating = float()
string = str()
boolean = bool()

If we then print out the object type for each variable we get:

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

Here you can see the default initialized value for these four classes: for int it is 0, for float it is 0.0, for str it is a blank entry, and for bool it is False.

3.6. Concluding thoughts#

These last two lessons 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 into Python!

3.7. Want to learn more?#

Python Software Foundation - Standard Library Types
Python Software Foundation - Built-in Functions
W3Schools - Python Tutorial