Functions, Modules, and the Python Standard Library

Content

  • Functions
  • Modules
  • Python Standard Library

Functions

(see https://docs.python.org/2/tutorial/controlflow.html#defining-functions)

Functions increase the modularity and functionality of your code. Create functions for pieces of code that you will use more than once. That makes your code easier to read.


In [1]:
def area_circle(radius, pi=3.14):
    """determine area of a circle, given its radius"""   # documentation! 
    return pi*radius*radius

print area_circle(3) # uses the default value of 'pi'
print area_circle(3, pi=3)  # uses your own value of 'pi'
print area_circle.__doc__


28.26
27
determine area of a circle, given its radius

Note that code that is part of a function has to be indented. return literally returns some value that replaces the function call - in this case, it acts as an argument to print. A documentation line briefly describing what the function does is a sign of good manners and useful to other people using your code.

A special case of function is a lambda function. It allows for defining so-called "inline" functions in your code:


In [2]:
area = lambda r: 3.14*r*r
area(3)


Out[2]:
28.259999999999998

Python supports "functional programming", which means that functions can be passed as arguments to other functions:


In [3]:
print map(lambda x: x+3, range(10))


[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Modules

(see https://docs.python.org/2/tutorial/modules.html)

Modules provide additional functionality. Importing modules allows you to access functions, variables, and other things defined within their "namespace". The namespace concept is important to understand how to use modules properly.


In [4]:
a = 3
print dir()


['In', 'Out', '_', '_2', '__', '___', '__builtin__', '__builtins__', '__doc__', '__name__', '_dh', '_i', '_i1', '_i2', '_i3', '_i4', '_ih', '_ii', '_iii', '_oh', '_sh', 'a', 'area', 'area_circle', 'exit', 'get_ipython', 'quit']

dir() prints all elements in the current namespace of your program (e.g., variable a). Your namespace contains all functions, variables, etc. that you have created as part of your code.

Let's come back to modules. There are different ways to import modules that have different effects on your namespace. This is the easiest way:


In [5]:
import math
dir(math)


Out[5]:
['__doc__',
 '__name__',
 '__package__',
 'acos',
 'acosh',
 'asin',
 'asinh',
 'atan',
 'atan2',
 'atanh',
 'ceil',
 'copysign',
 'cos',
 'cosh',
 'degrees',
 'e',
 'erf',
 'erfc',
 'exp',
 'expm1',
 'fabs',
 'factorial',
 'floor',
 'fmod',
 'frexp',
 'fsum',
 'gamma',
 'hypot',
 'isinf',
 'isnan',
 'ldexp',
 'lgamma',
 'log',
 'log10',
 'log1p',
 'modf',
 'pi',
 'pow',
 'radians',
 'sin',
 'sinh',
 'sqrt',
 'tan',
 'tanh',
 'trunc']

In order to address any element in the math namespace, you have to specifically tell Python that this element is in the math namespace:


In [6]:
#sqrt(4)     # will cause a NameError, as sqrt is not defined in your namespace
print math.sqrt(4)


2.0

You can rename namespaces of modules upon importing them:


In [7]:
import math as m
print m.sqrt(9)


3.0

Or you can import the entire namespace of a module in your namespace:


In [8]:
from math import *
print sqrt(16)


4.0

However, this is dangerous, as you might up with a namespace where different things share the same name. Try not to use from XXX import *. Instead, you can import specific things of which you know that you will use them more often:


In [9]:
from math import sqrt
print sqrt(36)


6.0

The Python Standard Library

This is just a quick introduction of some libraries that you might want to use regularly in the future. See https://docs.python.org/2/library/index.html#library-index for more details.

Math

(see https://docs.python.org/2/library/math.html)


In [10]:
import math

print math.pi
print math.sqrt(4)       # square root
print math.fabs(-3.13)   # absolute value (for floats)
print math.exp(1)        # exponential function
print math.log(math.e)   # natural log
print math.log10(100)    # base-10 log   
print math.cos(0)        # cosine
print math.sin(math.pi)  # sine


3.14159265359
2.0
3.13
2.71828182846
1.0
2.0
1.0
1.22464679915e-16

os (Operating System)

(see https://docs.python.org/2/library/os.html)


In [11]:
import os

print os.getcwd()       # get the current working directory
os.chdir('../')   # change the current working directory
print os.listdir('.')   # list files and directories in this directory
os.mkdir('/tmp/test')  # create directory
os.rmdir('/tmp/test')  # remove directory
os.access('test.dat', os.F_OK) # check if file exists
os.remove('test.dat') if os.access('test.dat', os.F_OK) else None # remove a file if it exists
#os.abort()        # abort code execution


/home/mommermi/nau/teaching/2016Fall_Python/Introduction-to-Python-for-Scientists/notebooks
['assignments', '.gitignore', 'LICENSE', 'notebooks', '.git', 'readme.rst', 'introduction.pdf']

A powerful script that walks from a specific directory downwards:


In [ ]:
for root, dirs, files in os.walk('.'): 
    print 'in', root
    print '  files', files

datetime (Basic date and time types)

(see https://docs.python.org/2/library/datetime.html)


In [13]:
import datetime

a = datetime.datetime.now()      # current time (local time)
b = datetime.datetime.utcnow()   # current time (UT)

print a + datetime.timedelta(minutes=30)  # add 30 minutes to datetime object

a_str = a.strftime("%d/%m/%y %H:%M:%S")   # nicely format datetime object
print datetime.datetime.strptime(a_str, "%d/%m/%y %H:%M:%S") # convert string to datetime object


2016-09-29 15:43:11.307719
2016-09-29 15:13:11

time (Simple Time Operations - good enough for a Stopwatch)

(see https://docs.python.org/2/library/time.html)


In [14]:
import time

start = time.time()
# do stuff
print time.time()-start # number of seconds it took the code to run


7.00950622559e-05

urllib2 (Library for dealing with URLs)

(see https://docs.python.org/2/library/urllib2.html)


In [15]:
import urllib2

url = 'http://nearearthobjects.nau.edu/neosurvey/results.html'
a = urllib2.urlopen(url).readlines()  # grab website source code 
#print  a

subprocess (Run External Programs)

(see https://docs.python.org/2.6/library/subprocess.html)


In [16]:
import subprocess

subprocess.Popen(['ls', '-1'])  # call 'ls -1'

s = subprocess.Popen(['ls', '-1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # call 'ls -1' and catch the screen output
s.wait()        # wait for s to end
output = s.communicate()[0].split('\n')
print output


['assignments', 'introduction.pdf', 'LICENSE', 'notebooks', 'readme.rst', '']