Lecture 2.1 Python Demos

These are the Python data structure demonstrations we did in class on Tuesday, January 26.

For those following along on the Internet: a lot of the order was driven by class questions. We had a good, conversational time, with lots of students asking if you could do different things and the answers coming in the notebook.

Basic Types and Variables

Basic scalar types - we can just assign variables.

In [1]:
a_number = 2
a_string = 'hello'
a_boolean = False

The print function lets us print out variables.

In [2]:
print(a_number)
2
In [3]:
print(a_string)
hello

We can also use floating-point numbers. Jupyter (the notebook thing I am using) displays the value of the last expression, using the Python syntax that would be required to write it:

In [4]:
a_number = 3.5
a_number
Out[4]:
3.5

Lists

Python has lists as a built-in feature. This creates an empty list.

In [5]:
a_list = []
a_list
Out[5]:
[]

And we can add to lists:

In [6]:
a_list.append('squirrel')
In [7]:
a_list
Out[7]:
['squirrel']

Accessing a list works just like array access in C++ — 0-based indexes:

In [10]:
a_list[0]
Out[10]:
'squirrel'

An out-of-range index gives us a clean error:

In [11]:
a_list[1]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-11-3df459e7e5d7> in <module>()
----> 1 a_list[1]

IndexError: list index out of range

The len function tells us the length of a thing for which length is relevant (lists, strings, dictionaries, etc.):

In [12]:
# how big is it?
len(a_list)
Out[12]:
1

We can add more things, and replace existing values using indexing and assignment.

In [13]:
a_list.append('racoon')
a_list[0] = 'skunk'
a_list
Out[13]:
['skunk', 'racoon']

We can also directly write lists with their contents.

In [14]:
a_list = ['woozle', 'splintercat', 'left-handed sidewinder']
a_list
Out[14]:
['woozle', 'splintercat', 'left-handed sidewinder']

Python loops iterate over lists. Each time through the list, the variable animal is assigned to a different member of the list:

In [17]:
for animal in a_list:
    print('I smell a', animal)
I smell a woozle
I smell a splintercat
I smell a left-handed sidewinder
In [18]:
animal
Out[18]:
'left-handed sidewinder'

If we wanted to iterate by index, like you do in C++, we could do it like this:

In [20]:
for i in range(len(a_list)):
    print('I smell a', a_list[i], end=' ')
I smell a woozle I smell a splintercat I smell a left-handed sidewinder 

Dictionaries

Python dictionaries map arbitrary keys to values. They are like lists, sort-of, except they work with keys (strings or numbers, usually) instead of integer positions:

In [21]:
a_dict = {'HACKEM MUCHE': 'identify', 'READ ME': 'scare monster'}
a_dict
Out[21]:
{'HACKEM MUCHE': 'identify', 'READ ME': 'scare monster'}
In [22]:
a_dict['HACKEM MUCHE']
Out[22]:
'identify'
In [23]:
a_dict['FOOBIE BLETCH'] = 'enlightenment'
In [24]:
a_dict
Out[24]:
{'FOOBIE BLETCH': 'enlightenment',
 'HACKEM MUCHE': 'identify',
 'READ ME': 'scare monster'}

Dictionaries have a method, keys, that returns a list of keys:

In [25]:
a_dict.keys()
Out[25]:
dict_keys(['READ ME', 'HACKEM MUCHE', 'FOOBIE BLETCH'])

We can sort lists with the sorted function, that returns a copy of the list in sorted order:

In [26]:
sorted(a_dict.keys())
Out[26]:
['FOOBIE BLETCH', 'HACKEM MUCHE', 'READ ME']

So, if we want to iterate over the dictionaries contents and print them sorted by key:

In [27]:
for key in sorted(a_dict.keys()):
    print('The scroll called {} is {}'.format(key, a_dict[key]))
The scroll called FOOBIE BLETCH is enlightenment
The scroll called HACKEM MUCHE is identify
The scroll called READ ME is scare monster

We can also iterate over the key-value pairs (items) in the dictionary:

In [30]:
for key, value in a_dict.items():
    print('The scroll called {} is {}'.format(key, value))
The scroll called READ ME is scare monster
The scroll called HACKEM MUCHE is identify
The scroll called FOOBIE BLETCH is enlightenment

items actually returns a list of tuples, in this case (key, value) pairs. We can see this if we dump the items themselves:

In [31]:
for item in a_dict.items():
    print('got', item)
got ('READ ME', 'scare monster')
got ('HACKEM MUCHE', 'identify')
got ('FOOBIE BLETCH', 'enlightenment')

The key, value syntax unpacks the tuples. We know that items returns a list of 2-element tuples, so we can write 2 variable names separated by commas so we can access them directly.

Also, this loop demonstrates a basic if statement:

In [32]:
for key, value in a_dict.items():
    if key[0] != 'R':
        print('The scroll called {} is {}'.format(key, value))
The scroll called HACKEM MUCHE is identify
The scroll called FOOBIE BLETCH is enlightenment

Let's only get the first 2 keys:

In [33]:
for i, key in enumerate(a_dict.keys()):
    if i >= 2:
        break
    print(key)
READ ME
HACKEM MUCHE

Python's ‘else-if’ construct is written elif:

In [36]:
for key, value in a_dict.items():
    if len(key) > 7:
        print('The scroll called {} is {}'.format(key, value))
    elif len(key) < 2:
        print('too short')
    else:
        print("We don't like {}".format(key))
We don't like READ ME
The scroll called HACKEM MUCHE is identify
The scroll called FOOBIE BLETCH is enlightenment

Misc

Python has an object None that represents nothing.

In [37]:
None

You can't really do anything with it.

In [38]:
None + 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-38-a7a3acba4d06> in <module>()
----> 1 None + 5

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Except test if something is/is not None:

In [39]:
if a_list is not None:
    print('not none!')
not none!

A1 Data

This section demonstrates some basic exploration of the Assignment 1 data.

We can load the data. play will be a dictionary containing all of the play's data:

In [41]:
import yaml
with open('shakespeare/muchado.yaml', 'r') as yf:
    play = yaml.load(yf)
In [42]:
play.keys()
Out[42]:
dict_keys(['id', 'date', 'title', 'acts', 'full_title', 'characters'])

Plays have titles:

In [43]:
play['title']
Out[43]:
'Much Ado about Nothing'

And characters

In [44]:
play['characters']
Out[44]:
{'1watchman-ma': 'First Watchman',
 '2watchman-ma': 'Second Watchman',
 'antonio': 'Antonio',
 'balthasar-ma': 'Balthasar',
 'beatrice': 'Beatrice',
 'benedick': 'Benedick',
 'borachio': 'Borachio',
 'boy-ma': 'Boy',
 'claudio': 'Claudio',
 'conrade': 'Conrade',
 'dogberry': 'Dogberry',
 'donjohn': 'Don John',
 'donpedro': 'Don Pedro',
 'friarfrancis': 'Friar Francis',
 'hero': 'Hero',
 'leonato': 'Leonato',
 'lord-ma': 'Lord',
 'margaret': 'Margaret',
 'messenger-ma': 'Messenger',
 'sexton-ma': 'Sexton',
 'ursula': 'Ursula',
 'verges': 'Verges',
 'watchman-ma': 'Watchman'}

And acts and scenes - this is the second scene of the first act:

In [47]:
play['acts'][0]['scenes'][1]
Out[47]:
{'act': 1,
 'blocks': [{'lines': ['[Enter LEONATO and ANTONIO, meeting]'],
   'speaker': None},
  {'lines': ['How now, brother! Where is my cousin, your son?',
    'hath he provided this music?'],
   'speaker': 'leonato'},
  {'lines': ['He is very busy about it. But, brother, I can tell',
    'you strange news that you yet dreamt not of.'],
   'speaker': 'antonio'},
  {'lines': ['Are they good?'], 'speaker': 'leonato'},
  {'lines': ['As the event stamps them: but they have a good',
    'cover; they show well outward. The prince and Count',
    'Claudio, walking in a thick-pleached alley in mine',
    'orchard, were thus much overheard by a man of mine:',
    'the prince discovered to Claudio that he loved my',
    'niece your daughter and meant to acknowledge it',
    'this night in a dance: and if he found her',
    'accordant, he meant to take the present time by the',
    'top and instantly break with you of it.'],
   'speaker': 'antonio'},
  {'lines': ['Hath the fellow any wit that told you this?'],
   'speaker': 'leonato'},
  {'lines': ['A good sharp fellow: I will send for him; and',
    'question him yourself.'],
   'speaker': 'antonio'},
  {'lines': ['No, no; we will hold it as a dream till it appear',
    'itself: but I will acquaint my daughter withal,',
    'that she may be the better prepared for an answer,',
    'if peradventure this be true. Go you and tell her of it.',
    '[Enter Attendants]',
    'Cousins, you know what you have to do. O, I cry you',
    'mercy, friend; go you with me, and I will use your',
    'skill. Good cousin, have a care this busy time.'],
   'speaker': 'leonato'},
  {'lines': ['[Exeunt]'], 'speaker': None}],
 'scene': 2,
 'title': 'A room in LEONATO’s house.'}

Note that the order of the keys is not preserved. Order of lists is.

In [ ]: