Munch Lab

Exercise: Files and Functions

This exercise is split into two parts: one that helps you train how you can make Python read and write files on your computer, and another that serve to build a familiarity with functions. Remember that purpose of the exercises is not to answer the questions in it but train the chain of thought that allows you to answer them. Play around with the code for each example and see what happens if you change it a bit.

Files

Reading files lets you access data that you can process with your code. Here we will just make a small example file that you can work on. So the first thing you should do is to create a file with text in it that you can read from your python script. Open your Sublime Text editor and type this in it:

This is the first line
This is the second line
This is the third line

Then save it in the same directory (folder) where you put your Python code and name it ‘file_to_read_from.txt’.

Exercise: reading from a file

To read from a file on your computer you need the name of the file. To create a connection between your script and the file you can use the built-in function open(). You call it like this:

f = open('file_to_read_from.txt', 'r')

The first argument to the open function is a string with the name of the file. The second argument is a string with one character in it. If you want to read from the file this must be an 'r'. If you want to write to the file it must be an 'w' (but don’t try this right now). In other words, you need to decide if you want to read from or write to a file before you open it. If you specify a name for a file that does not exist you will get an error. The open function returns a special type of value that points to the beginning of the file you have specified. Here we store it in the variable f.

To read all the content in a file you use the read() method which is associated with the file value. A method is actually a little pre-made function that is packaged together with a Python value. This may see strange at first but you will soon learn that all python values (also numbers and text) have methods that associate them with extra functionality. To call the read method on the file value that f points to you write f.read(). Notice the dot that connects f and read. This tells python that read is a method associated with the value in f. Here f.read() evaluates to the content of the file that f points to.

file_content = f.read()

Calling read() also makes f point to the end of the file (because you are done reading it). You can think of as an index finger pointing to the place in the file you are at. When you opened the file f pointed at the beginning. When you had read it using the read method you where at the end.

Write the code needed to open the file called 'file_to_read_from.txt', read its content into a variable, print the content, read the content again and print it again.

… open file …
… read content …
… print the content …
… read content again …
… print the content you read this time…

What happens the second time you try to read from the file, and why?

Exercise: reading from a file 2

The position in the file that f points to will change as you read the file (to keep track of how much of the file you have read). If you want it to point to a new place in the file – say if you want to read the from the beginning again – you can use the seek method. If you call f.seek(0) you will make the f point to position 0, which is the beginning of the file. Try to modify your code by inserting an f.seek(0) statement like this:

… open file …
… read content …
… print the content …
f.seek(0)
… read content again …
… print the content you read this time…

What happens not and how (and why) is it different from what the code produced before.

Exercise: reading from a file 3

Now try to modify your code so you use the readline method instead of the read method. What happens now?

Exercise: writing to a file

To write results produced by your script to a file on your computer, you need to open it in much the same way as when you wanted to read from a file. Only now you specify a 'w' as the second argument to the open method. Look at the code below and decide what it does before you copy it (no copy/paste), and run it. What is the name of the file that we write to? What is printed to the file? (open ‘file_to_write_to.txt’ in Sublime Text and see) What does '\n' represent? What does the close method do?

f = open('file_to_write_to.txt', 'w')
f.write('First line\n')
f.write('Second line\n')
f.close()

Now close ‘file_to_write_to.txt’ in Sublime Text. Try to modify the code to print ‘1. line’ and ‘2. line’ and run that. Then open ‘file_to_write_to.txt’ again and see what happens. I hope that you have now learned that if you open a file to write to that does not exist – then it is created for you. You should also have learned that if open a file to write to that already exists then the existing file replaced with an empty file that you can write to.

Functions

These exercises will train your familiarity with functions.

Exercise: show and tell. Refer to the lecture slides if necessary!

def power(a, b):
    print "This function computes %d**%d" % (a, b)
    return a**b

print power(4, 2)

What does this function do? How many parameters does it have? How many statements does the function have? What does the function print? How many values does it return? What is the difference between return and print?

Try (possibly strange) variations of the code like the ones below to better understand the contribution of each line of code. You can begin with:

def power(a, b):
    print "This function computes %d**%d" % (a, b)
    return a**b

power(4, 2)

and

def power(a, b):
    print "This function computes %d**%d" % (a, b)
    return a**b

result = power(4, 2)
print result

and

def power(a, b):
    "This function computes %d**%d" % (a, b)
    return a**b

print power(4, 2)

and

def power(a, b):
    print "This function computes %d**%d" % (a, b)
    a**b

print power(4, 2)
def power(a, b):
    print a**b
    return "This function computes %d**%d" % (a, b)

print power(4, 2)

and

def power(a, b):
    return a**b
    print "This function computes %d**%d" % (a, b)

print power(4, 2)

Exercise

Define a function called “diff” which takes two parameters, x and y, and returns the difference between x and y.

Example:
def diff(x, y):
   ….

diff(8, 2) # should return 6
diff(-1, 2) # should return -3

Exercise

Define a function called “all_equal” that takes five arguments and returns True if all five arguments have the same value and False otherwise. The function should work with any input, for example:

all_equal("Dan", "Dan", "Dan", "Dan", "Dan")
all_equal(0, 0, 0, 0, 0)
all_equal(0.5, 0.5, 0.5, 0.5, 0.5)
all_equal(True, True, True, True, True)

Hint: You test equality with a == b. Now think back to what you learned about logic. Which operator can you use to ensure that a == b and b == c?

Exercise

Define a function called “is_even” which takes one argument and returns True if (and only if) this is an even number.

is_even(8) # should return True
is_even(3) # should return False

Exercise

Define a function called “is_odd” which takes one argument and returns True if (and only if) the argument is an odd number.

is_odd(8) # should return False
is_odd(3) # should return True

Can you use the function you just defined, is_even, to complete this exercise? How? Why is that a good idea?

Exercise

Define a function called “is_nucleotide_symbol” which takes one argument and returns True if this is either A, C, G, T, a, c, g or t, and False in any other case.

Name your parameters something sensible… e.g. symbol..

is_nucleotide_symbol("A") # should return True
is_nucleotide_symbol("B") # should return False
is_nucleotide_symbol("Dan sucks") # should return False
is_nucleotide_symbol("") # should return False

Exercise

Define a function called “is_complementary_base” which takes two parameters, base1, base2, and returns True if base2 is the complementary of base1, and False otherwise.

is_complementary_base("A", "G") # should return False
is_complementary_base("A", "T") # should return True
is_complementary_base("T", "A") # should return False
is_complementary_base("Dan sucks", "A") # should return False

Can you use the function you defined in the previous exercise to complete this exercise? How? Why is that a good idea?

Exercise

Define a function called “is_series_cool” which takes one parameter, tv_series, and returns True if (and only if) the parameter is either the string “Dr Who”, “Doctor Who” or “Narcos”.

is_series_cool("Days of our Lives") # should return False
is_series_cool("Doctor Who") # should return True
is_series_cool(42) # should return False

Exercise: functions in expressions

Consider this function definition that takes a single number as argument:

def square(n):
    return n**2

What does it do? What does it return? What number does square(2) then represent?

Below I have used it in some expression that are printed. Make sure you understand what each expression evaluates to. Do the explicit substitutions and replacements on paper before you run it. Remember that we can substitute a function call (like square(2)) for the value it returns, just like we can substitute a variable x for the value it points to.

print square(3)
print square(2 + 1)
print square(2) * 2 + square(3)
print square(square(2))
print square(2 * square(1) + 2)

Exercise: not for the faint-hearted

You already made a function that computes Fahrenheit from Celcius. You could do that because you knew the linear relationship between the two (you knew the slope and the intercept that defined Fahrenheit as a linear function of Celcius).

If you where to make a function makes this computation it could look like this:

def conversion(celcius):
    slope = 5/9.0
    intercept = 32
    return celcius * slope + intercept

Try to change this function so it takes three arguments, corresponding to celcius, slope and intercept so you can call it like this to convert 27 degrees celcius: conversion(37, 5/9.0, 32). Now you have a function that can do any linear conversion that you can put inside an other function like this:

def celcius2fahrenheit(celcius):
    return conversion(celcius, 5/9.0, 32)

Now try to extend this to a different problem: It has been found that the height and weight of a person are related by a linear equation with slope = 0.55 and intercept = -25. Define a function called “predict_weight” which takes just one argument, the height of a person, and returns the estimated weight of the person.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: