Modules

r = 5.6
pi = 3.1415
print("Circumference:", 2 * pi * r)

 

from math import pi
r = 5.6
print("Circumference: ", 2 * pi * r)

 

  • In module math π is already (with full accuracy) defined
  • import loads its functionality from module math

 

  • There exist many useful additional modules which can be imported with:
    import <module_name>
  • Examples:
    • import math / from math import pi
    • import numpy
    • import Bio / from Bio import SeqIO
    • ...
  • These modules need to be installed separately

 

  • Own modules can be written
    • For this a Python file with the name of the module is written, which can be used by other programs

Dist.py

# Module implements
# distance function

def d(a, b):

distance = 0

for i in range(len(a)):

if (a[i] != b[i]):

distance += 1

return distance
  • import can load parts of the module (import d from Dist) or the entire module (import Dist)
# Calculates distance

import Dist # loads module
A = "GATCGTTCG"
B = "CATGGTTGA"
dist = Dist.d(A,B)