Lecture 8 - Data Types

Lecture Date: Friday, February 5

Writing a program is like building with Legos.

Follow me on this: a program can be a large, complex thing, or a relatively small, compact thing. So can the things you build out of Legos. However, even the biggest Lego sculpture has something in common with the smallest little Lego building - they are both made with the same kinds of individual pieces. Sure, there are special pieces that only do certain things, but for the most part, it’s (pardon the pun) all the same building blocks.

What are the component building blocks of writing programs? Data types. Specifically, each different type of block is a different data type. Each data type is a category that specifies what kind of data is stored within it.

In most programming languages, there is a set of built-in data types. The built-in data types for Python that we’ll care most about include the following (there are others not included in this list as they are used for more specialized functions):

  • int - used for whole integer numbers
  • float - used for decimal numbers, also called floating point numbers (hence the float name)
  • str - used for strings, which is a sequence of characters
  • bool - short for boolean, used to hold either True or False
  • list - used to store multiple values of other data types in an ordered sequence
  • set - like a list, but unordered
  • dict - short for dictionary, this data type stores info in key/value pairs

int, float, and str are called immutable data types because once they are set, they cannot change their value. This doesn’t mean you can’t reassign a variable with this type - it just means that it is going to point to somewhere else in memory.

list, set, and dict are called mutable because they can be changed in the same place in memory.

We will review creating variables and how this is handled in memory.

Other topics we’ll cover:

  • built-in methods, like len(), type(), int(), float(), str()
  • using mathematical operands with strings
  • checking for equality (name vs. content with is and ==)
datatypes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Mark Sherriff (mss2x)

hungry = True
ready_for_weekend = True

print(hungry == ready_for_weekend)

print("Mark" * 7)

string = "This is my name!"

number = 3

print(type(number))
print(type(str(number)))

floater = number + 4.34
print(type(floater))

print(type(number + 3))

print(type(number == 4))
print(number == 4)
print((number == 4) == False)
print(type((number == 4) == False))

print(number < 4)

print(number < 4 and type(number) == type(3))

print(number > 5 or type(number) == type(3))

print(type(type(number == 4)))

print(type(number) is int)

a = 'Mark'
b = "".join(['Ma', 'rk'])
print(a == b)
print(a is b)