Exercises

Playing with the interpreter

Try to execute some simple statements and expressions (one at a time) e.g

print("Hello!")
1j**2
1 / 2
1 // 2
5 + 5
10 / 2 + 5
my_tuple = (1, 2, 3)
my_tuple[0] = 1
2.3**4.5

Do you understand what is going on in all cases?


In [ ]:

Most Python functions and objects can provide documentation via help function. Look the documentation of e.g open function with help(open)


In [ ]:

Play with tabulator completion, by typing just pr and pressing then tabulator key. Pressing Shift-tab (after finalising completion) one sees also short documentation about the function or object. This works also on variable names, try e.g.

my_extremely_long_variable_name = 5
my <TAB>

In [ ]:

Basic syntax

Try to assign the value 6 to the following variable names ` first-name family_name 3PO ____variable inb4tool8 print in

Which of them are valid to assign to?

Extra: why do you think the ones that cause an error are not valid? What's the reason?


In [ ]:

You probably noticed that even though print is a method in the namespace it was still valid to create a variable called print. If you now try to actually print something, you will get an error. For built-in functions (such as print) one can recover with the following code


In [ ]:
print = __builtin__.print
print("hello")

Are the following pieces valid Python code?

Case 1

numbers = [4, 5, 6, 9, 11]
sum = 0
for n in numbers:
    sum += n
  print("Sum is now"), sum

Case 2

x = 11
test(x)

def test(a):
    if a < 0:
        print("negative number")

In [ ]:

Tuples and lists

  1. Create a tuple called mytuple, with the following strings: "sausage", "eggs" and "bacon"
  2. check it's type using type()
  3. Create than a list called mylist with the same contents. You use can the normal list definition syntax ([]) or coerce it from the tuple with the list() function.

In [ ]:

Attempt to append the string "spam" to mylist and mytuple using append.


In [ ]:

List objects have a sort() function, use that for sorting the list alphabetically (e.g. mylist.sort() ). What is now the first item of the list?

Next, remove the first item from the list, investigate the contents and remove then last item from the list.


In [ ]:

Slicing

Using range() create a list that has the numbers from 50 to 0 with a step of -2. Note that in Python 3 range() returns an iterator (we'll discuss iterators more later on), list(range(args)) returns an actual list.


In [ ]:

Using slicing syntax, select

  • the last 4 items from the list
  • the items from index 10 to index 13
  • the first 5 items from the list

In [ ]:

Read up on the stride syntax . Then using it select

  • every third value in the list
  • the values with an odd-numbered index in the list

In [ ]:

Multidimensional lists

Create a two dimensional list of (x,y) value pairs, i.e. arbitrary long list whose elements are two element lists.

Are you able to use slicing for extracting only the y values? (Answer is no, but try it in any case)


In [ ]:

Dictionaries

Create a dictionary whose keys are the fruits “pineapple”, “strawberry”, and “banana”. As values use numbers representing e.g. prices.

Add “orange” to the dictionary and then remove “banana” from the dictionary. Investigate the contents of dictionary and pay attention to the order of key-value pairs.


In [ ]:

Bonus exercises

Create a new “fruits” dictionary where the values are also dictionaries containing key-value pairs for color and weight, e.g.

fruits['apple'] = {'color':'green', 'weight': 120}

Change the color of apple from green to red


In [ ]:

It is often useful idiom to create empty lists or dictionaries and add contents little by little.

Create first an empty dictionary for a mid-term grades of students. Then, add a key-value pairs where the keys are student names and the values are empty lists.

Finally, add values to the lists and investigate the contents of the dictionary.


In [ ]: