Exercise #3 - Python Fundamentals

Objectives

    • Hands-on exploration of key Python fundamentals

Exploration of key Python concepts

In this exercise, you will briefly explore some of the data and control structures presented in the Python Fundamentals component of the course. Unless stated otherwise, all activities will be performed with IPython.

Strings

    • Create a string of the characters abcdefghij, then print out some substrings, making sure you understand that printing a slice of [i:j] will print the characters starting at index i, up to but not including index j

e.g.

In [1]: s = 'abcdefghij'

In [2]: print s[4:7]

efg

  • Extract two substrings and then concatenate them together with the '+' operator. For example, extract 'def' and 'cde', assigning each to a new variable, then add the two variables together to create a new string

  • Remembering that strings are immutable, see what happens when you try to modify one of the elements of a string - for example, try

s[6] = 'x'

    • Try the following code, and then modify so that it will print correctly

In [3]: n = 43

In [4]: s = 'The number is: '

In [5]: print s + n

Lists

Create a list of names, for example

In [6]: x = ['Vienna', 'Munich', 'Bratislava']

Then, use the list reverse() method to reverse the order, and the sort() method to sort the list, observing the modified lists after each operation.

In your list, print every other element by using a slice. As a hint, look at the following code for printing every third element.

In [9]: y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [10]: y[::3]

Out[10]: [1, 4, 7, 10]

File input and for loop

The following file (also available at bottom of this page)

/home/kurs/donmor/Files/Exercise03/metrecords.txt

contains three weather observation records. Each record consists of the location name, timestamp, temperature and windspeed.

Copy the file into your directory, then open it and assign it to a file handle

In [2]: fh = open('metrecords.txt', 'r')

  • Using the readline() method for the file handle object, read the first line of the file into a variable and print it. You should see a single string with all four fields

  • Using the split() method for the string you just read, create a list of the fields (tokens), assign the list to a variable, and print it. What you should now see is a list that contains four strings, corresponding to the four fields of the record

  • Assign the temperature field to a variable, and use the type() function to verify that it is type str.

An example of using type():

In [7]: s = 'ZAMG'

In [8]: type(s)

Out[8]: str

    • Convert the temperature to type float, store it in a new variable, and use the type() function again to verify that you did it correctly

    • Close the file, and then open it again (this resets the file pointer to the top of the file)

    • Now, create a for loop to read and print each line

In [10]: for record in fh:

....: print record

....:

Fairbanks 201604021153 -3.7 0.1

Vienna 201604021132 10.1 12.9

Salzburg 201604021146 7.4 1.3

Using zip() for parallel lists

Recall the zip() function that allows for iterating through a set of parallel arrays, as demonstrated in the following example:

In [1]: x = [1.0, 2.0, 3.0]; y = [3.0, 2.0, 1.0]

In [2]: for a, b in zip(x, y):

...: print a, b

...:

1.0 3.0

2.0 2.0

3.0 1.0

Create your own lists of numbers, both the same length. Then, use a loop to compute the sum of the differences between the lists and, after the loop, using the length of one of the lists (remember the len() function), calculate the average difference. In the above example, the sum of the differences is zero, and therefore the average difference is 0.

Use of modules and functions

You are being provided with a module, pairs.py, that currently has only a single function, sum(), defined in it. The function expects two lists of numbers as arguments, and will return a new list containing the pairwise sum of the argument lists, for example:

In [1]: import pairs

In [2]: u = [1, 1, 1, 1]

In [3]: v = [2, 2, 2, 2]

In [4]: w = pairs.sum(u, v)

In [5]: print w

[3, 3, 3, 3]

The module is available in /home/kurs/donmor/Files/Exercise03/, and at the bottom of this page. First, make sure that you can import it into IPython and use it with your own lists of numbers.

Then, in a separate window, explore the module pairs.py. First, note that there is test code at the bottom, and that you should be able to run the module by itself to verify that it works.

$ python pairs.py

a + b: [5, 7, 9]

Then, you should add a new function to the module, mult(), that returns a new list containing the pairwise product of the argument lists. Create a new test at the bottom of the module for this new function, and verify that it works. In this way, every time that you modify or add to the module, you can test it by itself.

Next, import your module into IPython and make sure you can call both the add() and mult() functions successfully. Note that if you already have IPython open and had previously imported pairs, your new changes have not been included. You can close and reopen IPython, then import again.

Then, create one more function, meandiff(), which calculates the average difference between the two lists (as you did above) and returns that value. As before, put a test at the bottom of the module and test it that way first, then make sure you can run it from IPython.

Brief exposure to dict and list of dict

Using the following as an example, you should create 2 or more dictionaries with identical fields, and put them in a list, then verify that you can print the contents of the list:

In [6]: d1 = {'city' : 'Vienna', 'degC' : 27.3}

In [7]: d2 = {'city' : 'Graz', 'degC' : 19.6}

In [8]: obs = [d1, d2]

In [9]: for o in obs:

...: print o

...:

{'city': 'Vienna', 'degC': 27.3}

{'city': 'Graz', 'degC': 19.6}

Then, you should create a loop that will print two formatted columns - the city name and the temperature, for example

Vienna 27.3

Graz 19.6

I recommend that you work first on being able to print the city and temperature without formatting, and then once you've figured out how to print the dictionary elements, figure out how to format them. Just to help you out a little bit, here is sample code that demonstrates some formatting

In [10]: a = 1.451; b = 3; c = 'ZAMG'

In [11]: print '%3.1f %8s %3.1f' % (a, c, b)

1.5 ZAMG 3.0

Remember that if you want to left-justify a formatted string, you can put a minus (-) before the number of characters.