7  Datatypes

So far we have taken a look at functions, which are like verbs within the scope of our program.

However programs are also comprised of objects, which are like nouns within the scope of the program.

Each object belongs to a given data type. The data type of an object determines how the data is stored in memory, and more practically determines what operations we can perform with that object.

7.1 Python Datatypes

Python has a number of built-in datatypes, each of which represents a different kind of object.

In other words, knowing what datatype an object is allows us to understand exactly what we can do with that object.

7.1.1 Examples

Here is an example of each of the most popular datatypes. We will cover many of these datatypes and their operations in more detail, but for now just know what these datatypes look like.

7.1.1.1 Basic Datatypes

Basic ("scalar") datatypes that involve a single value:

Datatype Description Example
Boolean Two binary values which are the opposite of each other. True vs False only
Integer Numeric data (whole number) without decimal component. 5
Float Numeric data with a decimal component. 3.5
String Textual data, within quotes. "HELLO WORLD"
None Type Absence of a value, or a “null” value. None only

7.1.1.2 Container Datatypes

"Container" datatypes that can hold many values:

Datatype Description Example
List A sequence of values. Order matters. Can contain duplicates. Mutable (can be updated and changed). [5, 3, 1, 5]
Tuple A sequence of values. Immutable (cannot be changed). (5, 3, 1, 5)
Set Like a list, but without a particular order, and cannot contain duplicates. {5, 3, 1}
Dictionary An object with named attributes, otherwise known as “key value pairs”. {"first_name": "Michael", "last_name": "Jordan"}

7.2 Why Datatypes Matter

Let’s see an example of why datatypes matter. Consider the following example, where we are using the plus sign (+) operator with different datatypes.

When we use the plus sign operator with numbers, this will perform addition:

result = 2 + 2
print(type(result))
print(result)
<class 'int'>
4

However when we use the same plus sign operator with strings, this will perform what is known as a "concatenation" operation, which you may be familiar with from spreadsheet software:

result = "2" + "2"
print(type(result))
print(result)
<class 'str'>
22

Notice, if we are not paying attention to which datatypes we are using, we might run into errors and not be able to perform certain operations, or the operation will behave differently, perhaps in an unexpected way:

#print("2" + 2)  # DON'T
#> TypeError: can only concatenate str (not "int") to str

In this case, we tried to use the plus sign operator with mixed datatypes. Python threw an error because it doesn’t know what operation to perform. Should it perform addition? Or concatenation? This is why it is important to know what datatypes we are working with!

7.3 Datatype Detection Functions

In practice, whenever we start working with an object, it is always a good idea to ask what datatype it is. There are two main functions we can use to detect datatypes: the type function, and the isinstance function.

7.3.1 The type Function

The type function will output the name of the object’s datatype:

print(type(100))
print(type(4.5))
<class 'int'>
<class 'float'>
print(type("HELLO WORLD"))
<class 'str'>
print(type(True))
print(type(False))
<class 'bool'>
<class 'bool'>
print(type([1, 6, 3, 100]))
<class 'list'>
print(type({"first_name": "Michael", "last_name": "Jordan"}))
<class 'dict'>

7.3.2 The isinstance Function

Whereas the isinstance function will allow us to ask if an object is an instance of the specified datatype. This function will return either True or False.

print(isinstance(100, int))
print(isinstance(100, float))
print(isinstance(100, str))
print(isinstance(100, list))
print(isinstance(100, dict))
True
False
False
False
False

7.4 Datatype Conversion Functions

If you need to convert from one datatype to another, that is sometimes possible with eligible datatypes. Here are some examples of using built-in datatype conversion functions:

result = int("2")
print(type(result))
print(result)
<class 'int'>
2
result = float("2")
print(type(result))
print(result)
<class 'float'>
2.0
result = str(2)
print(type(result))
print(result)
<class 'str'>
2
result = bool(0) # 0 is False, 1 is True
print(type(result))
print(result)
<class 'bool'>
False
result = list("HELLO WORLD")
print(type(result))
print(result)
<class 'list'>
['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']
result = set([5, 3, 1, 3, 7]) # set conversion will remove duplicates from the list
print(type(result))
print(result)
<class 'set'>
{1, 3, 5, 7}

7.5 Object Oriented Programming

In Python, you will see a mix of functional and object-oriented syntax patterns.

Let’s consider an example object of a polo t-shirt, to exemplify these concepts.

Shelves of polo shirts with varying colors and sizes

In functional programming, the function is the star of the show, and we pass object(s) in as parameters. Here are some hypothetical examples of functional syntax in Python:

  • get_color(polo)
  • fold(polo)
  • ship_to_store(polo, "Boston, MA")

Whereas in object-oriented programming, the objects are the stars of the show, and we invoke methods and properties directly on them. Here are some hypothetical examples of object-oriented syntax in Python:

  • polo.color
  • polo.fold()
  • polo.ship_to_store("Boston, MA")

Characteristics of an “object” include:

  • Identity
  • Attributes / Properties
  • Behaviors / Methods

7.5.1 Identity

The concept of identity means that each polo is unique. For example we can have two large blue polos. Even though these objects seem similar, they are distinct, and we can operate on them separately. In other words, we can sell or fold one of them, and not the other.

7.5.2 Properties

Properties are attributes or characteristics of the object. For example, all polos will have a "size", a "color" and "price", even though their individual values may vary. In other words, we can have a yellow polo, and a blue polo, but they each have a "color". Generally, properties are nouns.

Here are some hypothetical examples of properties in Python (observe there are no trailing parentheses):

  • polo.color
  • polo.size

7.5.3 Methods

Methods are behaviors that an object can have. A method is like a function in the sense that it represents the performance of some action, or verb.

Here are some hypothetical examples of methods in Python (observe these require a trailing parentheses):

  • polo.fold()
  • polo.ship_to_store("Boston, MA")