Software Carpentry
Functions and Libraries


Introduction


You Can Skip This Lecture If...


Defining Functions


Returning Values


Everything Returns Something


Scope


Parameter Passing Rules


Making Copies


Default Parameter Values


Functions Are Objects


Function Object Examples


Function Attributes


Creating Modules


Module Scope


Other Ways to Import


Import Executes Statements


Knowing Who You Are


The System Library


Command-Line Arguments


Standard I/O


The Python Search Path


Exiting


The Math Library


Working with the File System


File and Directory Status


Manipulating Pathnames


Summary


Exercises

Exercise 9.1:

Write a function that takes two strings called text and fragment as arguments, and returns the number of times fragment appears in the second half of text. Your function must not create a copy of the second half of text. (Hint: read the documentation for string.count.)

Exercise 9.2:

What does the Python keyword global do? What are some reasons not to write code that uses it?

Exercise 9.3:

Python allows you to import all the functions and variables in a module at once, making them local name. For example, if the module is called values, and contains a variable called Threshold and a function called limit, then after the statement from values import *, you can then refer directly to Threshold and limit, rather than having to use values.Threshold or values.limit. Explain why this is generally considered a bad thing to do, even though it reduces the amount programmers have to type.

Exercise 9.4:

sys.stdin, sys.stdout, and sys.stderr are variables, which means that you can assign to them. For example, if you want to change where print sends its output, you can do this:

import sys

print 'this goes to stdout'
temp = sys.stdout
sys.stdout = open('temporary.txt', 'w')
print 'this goes to temporary.txt'
sys.stdout = temp

Do you think this is a good programming practice? When and why do you think its use might be justified?

Exercise 9.5:

os.stat(path) returns an object whose members describe various properties of the file or directory identified by path. Using this, write a function that will determine whether or not a file is more than one year old.

Exercise 9.6:

Write a Python program that takes as its arguments two years (such as 1997 and 2007), prints out the number of days between the 15th of each month from January of the first year until December of the last year.

Exercise 9.7:

Write a simple version of which in Python. Your program should check each directory on the caller's path (in order) to find an executable program that has the name given to it on the command line.

Exercise 9.8:

In the default parameter value example, why does total use a default value of None for end, rather than an integer such as 0 or -1?

Exercise 9.9:

What does the * in front of the parameter extras mean in the following code example?

def total(*extras):
    result = 0
    for e in extras:
        result += e
    return result

Hint: look at the following three examples:

print total()
print total(19)
print total(2, 3, 5)

Exercise 9.10:

Use the os.path, stat, and time modules to write a program that finds all files in a directory whose names end with a specific suffix, and which are more than a certain number of days old. For example, if your program is run as oldfiles /tmp .backup 10, it will print a list of all files in the /tmp directory whose names end in .backup that are more than 10 days old.

Exercise 9.11:

The previous lecture ended by showing several different ways to copy files using Python. Read the documentation for the shutil module, and see if there's a simpler way.

Exercise 9.12:

Consider the short program shown below:

def add_and_max(new_value, collection=[]):
    collection.append(new_value)
    return max(collection)

print 'first call:', add_and_max(22)
print 'second call:', add_and_max(9)
print 'third call:', add_and_max(15)

What do you expect its output to be? What is its actual output? Why?

Send comments