You are a guest. Restricted access. Read more

Modules

A Python module is a file containing Python code. Such files can contain classes, functions and constants. They can be can be grouped together in a package. Packages also serve to create separate namespaces so that two classes of the same name can exist and be used in the same code as long as they belong to different packages.

To start using modules, you will need to import them first using “import” command. We considered already such command at the very start of this tutorial in Sect.Arithmetic Let us repeat the previous example:


import math
print math.sqrt(100)

We imported the entire package “math” with mathematical functions. Or you may consider to import only one function:


from math import sqrt
print sqrt(100)

Alternatively, you simply import all functions (in this case you do not need to type “math.” on front of each statement


from math import *
print sqrt(100)

How do we know what is inside the package “math”? You can list all functions and classes implemented in this package calling the build-in function dir():


import math
print dir(math)

Let us consider another module “random” which generates random numbers:


import random
print dir(random)

Exercise: Import modules “os” and “sys” and print all the methods:


import os,sys
# your code goes here


import os,sys
print os.__doc__

python/modules.txt · Last modified: 2013/04/14 16:52 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0