# Data Types and Operations¶

## 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:

In [1]:
7

Out[1]:
7

Floating-point numbers:

In [2]:
3.5

Out[2]:
3.5

Numbers with scientific notation:

In [3]:
6.02e23

Out[3]:
6.02e+23

## Arithmetic Operations¶

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

In [4]:
5 + 2

Out[4]:
7
In [5]:
2 + 3 * 6

Out[5]:
20

As do parentheses:

In [6]:
(2 + 3) * 6

Out[6]:
30

The ** operator computes powers:

In [7]:
2 ** 5

Out[7]:
32

The math and numpy modules contain many math functions:

In [8]:
import numpy as np
np.log(20)

Out[8]:
2.995732273553991

## Variables¶

A variable lets us give a name to a value:

In [9]:
x = 7


Just assign - no declaration necessary.

Then we can use them:

In [12]:
x + 5

Out[12]:
7

Let's seen an example of changing the variable:

In [11]:
x = 2


## Strings¶

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

In [13]:
"Hello, world"

Out[13]:
'Hello, world'

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

In [14]:
"Hello, \"world\""

Out[14]:
'Hello, "world"'

## String Operations¶

+ concatenates strings:

In [15]:
'hello' + 'world'

Out[15]:
'helloworld'

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

In [16]:
'hello world'.split()

Out[16]:
['hello', 'world']

## Types¶

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

In [17]:
'maroon' + 5

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
----> 1 'maroon' + 5

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

We can convert to a string with the str function:

In [18]:
'maroon' + str(5)

Out[18]:
'maroon5'

## Operations¶

We've now seen 3 different kinds of operations.

An operator:

In [19]:
6 + 7

Out[19]:
13

A function, in this case from a module:

In [20]:
np.log(10)

Out[20]:
2.302585092994046

A method, a function attached to an object:

In [21]:
'hello world'.split()

Out[21]:
['hello', 'world']

## Lists¶

The split() method returned a list:

In [22]:
'hello world'.split()

Out[22]:
['hello', 'world']

We can write lists:

In [23]:
['martin', 'cross', 'gripps']

Out[23]:
['martin', 'cross', 'gripps']

## More with Lists¶

Let's save a list in a variable:

In [24]:
rowdy3 = ['martin', 'cross', 'gripps']


We can add to the list:

In [25]:
rowdy3.append('vogel')
rowdy3

Out[25]:
['martin', 'cross', 'gripps', 'vogel']

## List Members¶

Lists are indexed, starting with 0:

In [26]:
rowdy3[0]

Out[26]:
'martin'

They can be indexed backwards from the end:

In [27]:
rowdy3[-1]

Out[27]:
'vogel'

A slice takes multiple elements from a list:

In [28]:
rowdy3[1:3]

Out[28]:
['cross', 'gripps']
In [29]:
len(rowdy3)

Out[29]:
4

## Loops¶

We can loop over a list:

In [30]:
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):

In [31]:
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:

In [32]:
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.:

In [33]:
coords = (3, 5)
coords[0]

Out[33]:
3
In [34]:
coords[1]

Out[34]:
5

A tuple can be unpacked:

In [36]:
x, y, z = coords
x

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-4ddec07835a7> in <module>
----> 1 x, y, z = coords
2 x

ValueError: not enough values to unpack (expected 3, got 2)

## Dictionaries¶

A dictionary maps keys — often strings — to values:

In [37]:
diets = {
'rabbit': 'plants',
'dog': 'meat',
'vulture': 'carrion'
}


We can look up a value by its key:

In [38]:
diets['rabbit']

Out[38]:
'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:

In [39]:
rowdy3

Out[39]:
['martin', 'cross', 'gripps', 'vogel']
In [40]:
rowdy5 = rowdy3
rowdy5.append('amanda')
rowdy5

Out[40]:
['martin', 'cross', 'gripps', 'vogel', 'amanda']

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

In [41]:
rowdy3

Out[41]:
['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