Topics to be covered

  • Learn the basic vocabulary and grammar of Python (exam material):
    • Variables referring to objects
    • Types: int, list, string, set, dict, boolean
    • Conditionals: if, elif, else
    • Loops: for (and passive knowledge of while)
    • Functions: built-in functions and methods, defining your own functions
    • Using files

Boolean Expressions

Please determine for the following code snippets whether the output will be:

  1. False (of type bool)
  2. True (of type bool)

In [ ]:
print("test" != "testing")

In [ ]:
print(not False)

In [ ]:
print( (5 + 7) == 12)

In [ ]:
print( (5 + 7) in [5, 1, 11, 7, 17, 13])

In [ ]:
print(100 != '100')

In [ ]:
print( (5 + 17) <= 21)

In [ ]:
print('a' not in 'hello world')

In [ ]:
d = {'1': 1, '2': 2}
print(1 in d)

In [ ]:
d = {'1': 1, '2': 2}
print('1' in d.keys())

In [ ]:
print(not False == True)

In [ ]:
print( (1+4) > 5)

In [ ]:
d = {'1': 1, '2': 2}
print(len(d) == 2)

In [ ]:
any([])

In [ ]:
all([])

In [ ]:
letters = ['a','b','c','d']
numbers = [1,2,3,4,5]
all([len(letters) < 4,
     numbers[-1] == 5])

In [ ]:
letters = ['a','b','c','d']
numbers = [1,2,3,4,5]
any([letters[1] == 'a',
     4 in numbers])

In [ ]:
a_string = 'hello world'
all([a_string.replace('o', 'b', 1) == 'hellb world',
     len(a_string) == 11,
     a_string[2] == 'l'])

In [ ]:
a_list = ['a', 'b', 'c', 'd']
all([a_list.pop() == 'd',
     a_list[0] == 'a'])

Syntax

Answer the following questions:

  1. What is the difference between == and =?
  2. What is the difference between mutable and immutable?
  3. When do you use squared brackets?
  4. Explain in words what this means: 4 < x < 10
  5. Why would anyone want to use sets instead of lists?
  6. Consider the following string and list:

    a_string = "python is awesome" a_list = ["python", "is", "awesome"]

    Using this example, explain how the join() and split() methods complement each other.

  7. What are the two ways to create an empty dictionary?
  8. What would be a shorter equivalent notation for x = x + 1?
  9. What would be printed with this code?

    a_string = "python is awesome" print(a_string[7:11])

  10. What are the two building blocks of a dictionary?

Tracing

Below is a function that processes data from a morphological analyzer for Turkish. Here's an example of the data that needs to be processed:

'olmamak\tol<V><neg><vn:inf><N>\nolmamak\tol<V><neg><vn:inf><N><0><V><cpl:pres>\nolmamak\tol<V><neg><vn:inf><N><0><V><cpl:pres><3s>\n\n'

This data contains morphological information about the word olmamak (with two different analyses). The problem is that it's not yet suitable for further processing. So analyze_output() does that for us, returning the data in the form of a Python object that is easier to work with.

Please read this code (annotated with line numbers) and answer the questions below. We've not used str.splitlines() much in this course, but it's a method that splits a string on every newline character. Here's a small example:

  • Input: 'Hello\nWorld\n\n'.splitlines()
  • Output: ['Hello', 'World', '']

In [ ]:
def analyze_output(output):                          # 1
    "Analyze the output of the FST."                 # 2
    results = []                                     # 3
    for line in output.splitlines():                 # 4
        if line:                                     # 5
            word, analysis = line.split('\t')        # 6
            morph_data = analysis.split('<')         # 7
            base, *rest = morph_data                 # 8
            morph_feats = []                         # 9
            for feature in rest:                     # 10
                morph_feats.append(feature[:-1])     # 11
            entry = {'word': word,                   # 12
                     'base': base,                   # 13
                     'features': morph_feats}        # 14
            results.append(entry)                    # 15
    return results                                   # 16

Suppose we call the function like this:

output = 'olmamak\tol<V><neg><vn:inf><N>\nolmamak\tol<V><neg><vn:inf><N><0><V><cpl:pres>\nolmamak\tol<V><neg><vn:inf><N><0><V><cpl:pres><3s>\n\n'
result = analyze_output(output)

Question 1. What is the type and value of word on line 6, during the first iteration of the loop?


In [ ]:

Question 2. What is the type and value of base on line 6, during the first iteration of the loop?


In [ ]:

Question 3. What is the purpose of if line (line 5)? When does it evaluate to False?


In [ ]:

Question 4. What is the type and value of entry (line 12) after the first iteration of the loop?


In [ ]:

Question 5. What is the purpose of feature[:-1] on line 11? What does it do? (Use the first iteration of the loop as an example.)


In [ ]:

Question 6. What is the type and value of results on line 16, at the end of the function?


In [ ]:

Spot the error

Please explain for each of the problem cases below why they produce an error.


In [ ]:
# Problem 1
a_string = "python is awesome"
a_string[5] = 'X'
print(a_string)

In [ ]:
# Problem 2
names = ["Karin", "Paul"]
"Hello" + names

In [ ]:
# Problem 4
def say_hello(name)
    print("Hello", name)

say_hello("Sandy")

In [ ]:
# Problem 5
def replace_a_by_o(a_string):
    new_string = a_string.replace("a", "o")
    print(new_string)

replace_a_by_o('apples and bananas')
print(new_string)

In [ ]:
# Problem 6
fruit = ["apple", "banana", "mango"]
fruit.append(["pineapple", "strawberry"])
print(fruit[4])

In [ ]:
# Problem 7
for number in ["15", "2", "7"]:
    if number < 10:
        print(number, "is lower than 10")

In [ ]:
# Problem 8
shopping_list = {"apples": 5, "bananas": 2, "pineapples": 1}
for product in shopping_list.items():
    print(shopping_list[product])

In [ ]:
# Problem 9
shopping_list = {["apples", "bananas"]: 2, "pineapples": 1}
for product in shopping_list:
    print(product)

In [ ]:
# Problem 10
word = "bananas"
if word[0] = "b":
    print(word)

Built-ins

Which built-in method would you use to..

Open a file?


In [ ]:

Get text input from a user?


In [ ]:

Turn an integer into a string?


In [ ]:

Learn more about how to use a particular function?


In [ ]:

Get a copy of a list of numbers, ordered from low to high?


In [ ]:

Find out how many characters (including spaces etc.) are in a string?


In [ ]:

Code writing/completion

Imagine there are two files:

  1. words1.txt
  2. words2.txt

Each line in the file contains one word, e.g.:

attic
tearful
tailgate
hydraulically
unsparing
....

Both files contain 1000 lines.

In the cell below, please write the code to:

  1. loop through the file words1.txt
  2. remove the newline character from each line
  3. append the line (without newline character) to a list

In [ ]:

In the cell below, please write the code to:

  1. loop through the file words1.txt
  2. remove the newline character from each line
  3. append all lines that start with 'a', 'c', 'd', and 'z' to a list

In [ ]:

In the cell below, please write the code to:

  1. loop through the file words1.txt
  2. remove the newline character from each line
  3. replace all 'l' with 'b'
  4. replace all 'b' with 'a'
  5. append the results from each line to a list

In [ ]:

In the cell below, please write the code to:

  1. save all words in a set that occur in words1.txt

In [ ]:

In the cell below, please write the code to:

  1. save all words in a list that occur in both words1.txt and words2.txt

In [ ]:

In the cell below, please write the code to:

  1. count how many lines start with 't'

In [ ]:

In the cell below write the code to:

  1. write a function that returns for words1.txt a dictionary that combines all lines that start with the same beginletter in a list:
    {'a' : ['attic'],
    'h' : ['hydraulically'],
    't' : ['tearful', 'tailgate'],
    'u' : ['unsparing']
    }

In [ ]: