#### Previous topic

Script Files via Text Editors

#### Next topic

Expressions and Conditional Execution

# Modules¶

A module is just a file containing code that can be understood by Python

• Any script we write is a module
• Other modules come with the Python distribution
• And others are third party (see, for example, PyPi)

In this lecture we will focus on modules in the Standard library

• Bundled with every Python distribution
• Very comprehensive and high quality

Python philosophy:

• Keep the core language small (makes it clean and consistent)
• And put most functionality in the standard library

## The import Statement¶

The Python keyword import is used to access code in modules

Let’s look at some examples, using the math module from the standard library

### Importing the Module¶

One way to load the math module is as follows

>>> import math


Now we can use the objects defined in the module:

>>> math.e                # A float (Euler's number e)
2.7182818284590451
>>> math.exp(10)          # exp() is a function (the exponential function)
22026.465794806718
>>> math.pi               # A float
3.1415926535897931
>>> math.sqrt(100)        # Another function
10.0
>>> math.exp(math.log(10))
10.000000000000002
>>> math.cos(math.pi)
-1.0


Notice the syntax

• To access pi we type math.pi
• To access sqrt() we type math.sqrt() etc.

Collectively, pi, sqrt(), etc. are called attributes of math

To access attribute, type moduleName.attributeName

• E.g., math.pi

In IDLE and IPython, typing math. and then TAB lists attributes

• Very useful
• You can also try help(math)

### Importing Attributes Directly¶

>>> import math


then to access pi I need to type math.pi

An alternative is to import pi directly

>>> from math import pi
>>> pi
3.1415926535897931


We can import multiple attributes as follows

>>> from math import pi, e
>>> pi
3.1415926535897931
>>> e
2.7182818284590451


This is convenient if you want to use just one or two attributes of a library

In fact we can directly import all the attributes in math as follows

>>> from math import *
>>> pi
3.1415926535897931
>>> sqrt(4)
2.0


This method is not used so much by good programmers

• Suddenly there are lots of variables defined, and it’s hard to keep track

## Other Modules¶

Let’s look at some more modules in the standard library

### The Random Module¶

Examples

>>> import random
>>> random.uniform(0, 1)     # Uniform r.v. on (0,1)
0.91175197121395068
>>> random.uniform(0, 1)     # Another one, independent of first
0.86542825268640777
>>> [random.uniform(0, 1) for i in range(3)]
[0.83426715541997887, 0.067833169185644748, 0.22589302179038462]
>>> random.normalvariate(0, 1)  # Standard normal
-1.0375932163018793
>>> X = ['a', 'b', 'c', 'd']
>>> random.choice(X)
'b'
>>> random.choice(X)
'b'
>>> random.choice(X)
'c'
>>> X
['a', 'b', 'c', 'd']
>>> random.shuffle(X)
>>> X
['a', 'd', 'b', 'c']


### Others¶

The os module is for interacting with operating system

>>> import os
>>> os.getcwd()   # Returns the current working directory
'/home/john/sync_dir/teaching/kyoto_08'
>>> os.listdir('.')   # List files in current directory
['index.txt',
...


## Problems¶

Write the following as programs. (Suggested solutions below)

Problem 1:

• Simulate a draw from $$Y = \max \{|X_1|, \ldots ,|X_{10}|\}$$, where $$X_i \sim N(0, 1)$$

• And print out the result
• Hint: Use list comprehensions

Problem 2:

• Simulate a draw from $$Y \sim Bin(n, 0.5)$$ using random.choice()
• num of successes in n indep trials with success prob 0.5
• E.g., num of heads in n flips of fair coin
• The value of n is read in from the user at run time

### Solutions¶

Solution to Problem 1

import random

N = [random.normalvariate(0, 1) for i in range(10)]
M = [abs(x) for x in N]
Y = max(M)
print Y


Solution to Problem 2

import random

n = int(raw_input("What is the value of n? "))
C = 0, 1
M = [random.choice(C) for i in range(n)]
Y = sum(M)
print Y


Alternatively,

import random

n = int(raw_input("What is the value of n? "))