\(\renewcommand\AA{\unicode{x212B}}\)
## File: mymath.py ##
def square(n):
return n*n
def cube(n):
return n*n*n
def average(values):
nvals = len(values)
sum = 0.0
for v in values:
sum += v
return float(sum)/nvals
import
statement. Once the definitions
are imported we can then use the functions by calling them as
module.functionname
. This syntax is to prevent name clashes.## My script using the math module ##
import mymath # Note no .py
values = [2,4,6,8,10]
print('Squares:')
for v in values:
print(mymath.square(v))
print('Cubes:')
for v in values:
print(mymath.cube(v))
print('Average: ' + str(mymath.average(values)))
import
``module``as
``new-name`` can be used to have
the module referred to under a different name, which can be useful
for modules with long namesimport mymath as mt
print(mt.square(2))
print(mt.square(3))
module.functionname
syntax by using
an alternate version of the import statement,
from
``module``import *
. The functions can then be used
as if they were defined in the current file. This is dangerous
however as you do not have any protection against name conflicts when
using multiple modules.If the module lives within the same directory as the script that is using it, then there is no problem. For system modules, these are pre-loaded into pythons sys.path list.
For example the numpy module location is here
import numpy
print(numpy.__file__)
There are several ways to make modules available for import.
This environmental variable is used by python on startup to determine the locations of any additional modules. You can extend it before launching your python console. For example on linux:
export PYTHONPATH=$PYTONPATH:{Path to mymodule directory}
python
On windows, it would look like this
SET PYTHONPATH=%PYTHONPATH%;{Path to mymodule directory}
python
Another way to make modules available for import is to append their directory paths onto sys.path within your python session.
python
>>> import sys
>>> sys.path.append({Path to mymodule directory})
>>> import mymodule
import
statement. Some examples of two useful modules
are shown below.import datetime as dt
format = '%Y-%m-%dT%H:%M:%S'
t1 = dt.datetime.strptime('2008-10-12T14:45:52', format)
print('Day ' + str(t1.day))
print('Month ' + str(t1.month))
print('Minute ' + str(t1.minute))
print('Second ' + str(t1.second))
# Define todays date and time
t2 = dt.datetime.now()
diff = t2 - t1
Gives the output:
Day 12
Month 10
Minute 45
Second 52
import os.path
directory = 'C:/Users/Files'
file1 = 'run1.txt'
fullpath = os.path.join(directory, file1) # Join the paths together in
# the correct manner
# print stuff about the path
print(os.path.basename(fullpath)) # prints 'run1.txt'
print(os.path.dirname(fullpath)) # prints 'C:\Users\Files'
# A userful function is expanduser which can expand the '~' token to a
# user's directory (Documents and Settings\username on WinXP and
# /home/username on Linux/OSX)
print(os.path.expanduser('~/test')) # prints /home/[MYUSERNAME]/test on
# this machine where [MYUSERNAME] is
# replaced with the login
import numpy
import numpy
x = numpy.array([1.3, 4.5, 6.8, 9.0])
arange
, which is numpy’s counterpart to
range
, i.e. it creates an array from a start to and end with a
given incrementx = numpy.arange(start=0.0, stop=10.0, step=1.0)
import numpy
x = numpy.array([[1,2,3], [4,5,6], [7,8,9]]) # 3x3 matrix
print(x.ndim) # Prints 2
print(x.shape) # Prints (3L, 3L)
print(x.size) # Prints 9
Gives the output:
2
(3, 3)
9
import numpy
a = numpy.array( [20, 30, 40, 50] )
b = numpy.arange( 4 )
c = a-b
print(c)
Gives the output:
[20 29 38 47]
x = numpy.array([1,2,3,4,5])
avg = x.mean()
sum = x.sum()
sx = numpy.sin(x)