Data Types and Operations¶

This notebook contains the slides for the Data Types and Operations video. To download this notebook, click the “Download” button at the upper left (down arrow and disk drive), and click .ipynb.

Learning Outcomes¶

  • Understand basic Python data types and operations

  • Store Python objects in variables

  • Write simple Python code to do arithmetic

  • Perform basic operations with lists and dictionaries!

This slide deck is a notebook!

More resources linked in the class notes.

Numbers¶

Python supports numbers. We can write integers:

7
7

Floating-point numbers:

3.5
3.5

Numbers with scientific notation:

6.02e23
6.02e+23

Arithmetic Operations¶

The usual arithmetic operations (+, -, /, *) work as expected from math and other programming languages:

5 + 2
7
2 + 3 * 6
20

As do parentheses:

(2 + 3) * 6
30

Additional Operations¶

The ** operator computes powers:

2 ** 5
32

The math and numpy modules contain many math functions:

import numpy as np
np.log(20)
2.995732273553991

See that import? We have to import Python modules before we can use them. It is common to import NumPy with the np alias so it’s easy to reference.

Variables¶

A variable lets us give a name to a value:

x = 7

Just assign - no declaration necessary.

Then we can use them:

x + 5
12

Cells are executed in the order in which you run them, not the order in which they appear. If we had another cell that changed the value of x, and then we went back and re-ran the cell above this, it would show a different values.

This means it is easy to confuse yourself. Before submitting a notebook, make sure you get the correct answers re-running it from top to bottom.

Let’s seen an example of changing the variable:

x = 2

Strings¶

Python strings are written in double (") or single (') quotes — there is no difference.

"Hello, world"
'Hello, world'

Within a string, \ is an escape character, e.g. to include a quote:

"Hello, \"world\""
'Hello, "world"'

String Operations¶

+ concatenates strings:

'hello' + 'world'
'helloworld'

The split method separates a string into a list, by default on whitespace:

'hello world'.split()
['hello', 'world']

Types¶

Python is strict about types - it won’t auto-convert:

'maroon' + 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\MICHAE~1\AppData\Local\Temp/ipykernel_26384/380687750.py in <module>
----> 1 'maroon' + 5

TypeError: can only concatenate str (not "int") to str

We can convert to a string with the str function:

'maroon' + str(5)
'maroon5'

Operations¶

We’ve now seen 3 different kinds of operations.

An operator:

6 + 7
13

A function, in this case from a module:

np.log(10)
2.302585092994046

A method, a function attached to an object:

'hello world'.split()
['hello', 'world']

These are the three primary ways of performing operations in Python.

In this class, we will write functions. Towards the end, we will write classes with methods. It is also possible to write your own implementations for operators (that’s how Pandas and NumPy work), but doing so is outside the the scope of this class.

Lists¶

The split() method returned a list:

'hello world'.split()
['hello', 'world']

We can write lists:

['martin', 'cross', 'gripps']
['martin', 'cross', 'gripps']

More with Lists¶

Let’s save a list in a variable:

rowdy3 = ['martin', 'cross', 'gripps']

We can add to the list:

rowdy3.append('vogel')
rowdy3
['martin', 'cross', 'gripps', 'vogel']

The rowdy3 line is to show the resulting list. Remember that Jupyter notebooks show the value of the last expression in the cell.

append on its own doesn’t return anything, but having a last line consisting of the variable name shows the list.

The append method modifies the list. The list is there, and it is the same list object, but it has been modified to contain another element.

List Members¶

Lists are indexed, starting with 0:

rowdy3[0]
'martin'

They can be indexed backwards from the end:

rowdy3[-1]
'vogel'

A slice takes multiple elements from a list:

rowdy3[1:3]
['cross', 'gripps']
len(rowdy3)
4

It starts with the first index, and takes up to but not including the last index.

Loops¶

We can loop over a list:

for person in rowdy3:
    print(person)
martin
cross
gripps
vogel

Loops 2¶

Let’s see 2 more tricks - including the position in our loop, and including variables in a string (an f-string):

for i, person in enumerate(rowdy3):
    print(f'Member {i}: {person}')
Member 0: martin
Member 1: cross
Member 2: gripps
Member 3: vogel

Loops 3¶

Python for loops iterate over an iterable, like a list.

To loop over a sequence of numbers, use a range:

for i in range(3):
    print(i)
0
1
2

Tuples¶

A Python tuple is like a list, except its size cannot be changed. Used for representing pairs, etc.:

coords = (3, 5)
coords[0]
3
coords[1]
5

A tuple can be unpacked:

x, y = coords
x
3

enumerate, in the previous slide, iterates over tuples of (position, item).

Dictionaries¶

A dictionary maps keys — often strings — to values:

diets = {
    'rabbit': 'plants',
    'dog': 'meat',
    'vulture': 'carrion'
}

We can look up a value by its key:

diets['rabbit']
'plants'

Objects¶

Everything in Python is an object, which has a type.

We’ve seen these types:

  • int

  • str (string)

  • list

  • tuple

  • dict (dictionary)

There is a lot more to do with these - see the readings!

References¶

Variables store references to objects. This matters for mutable objects:

rowdy3
['martin', 'cross', 'gripps', 'vogel']
rowdy5 = rowdy3
rowdy5.append('amanda')
rowdy5
['martin', 'cross', 'gripps', 'vogel', 'amanda']

But rowdy5 and rowdy3 are references to the same list object:

rowdy3
['martin', 'cross', 'gripps', 'vogel', 'amanda']

Ways to Learn¶

  • These videos, but will not be complete

  • Textbook (Chapters 2–3 on Python)

  • Python Tutorial

  • Learn Python the Hard Way

Wrapping Up¶

  • Python supports many data types

  • Everything is an object

  • Variables store references to objects