BeginnersTutorial:Tutorial/Lesson 8

From jWork.ORG
Jump to: navigation, search



A Python module is a file containing Python code written by others (or by you). Such files can contain any piece of code, 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. Here is a small example that imports "square root" function.

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)

There are two important module: "os" and "sys". The "os" module in Python provides a way of using operating system functions, i.e. it can help to talk directly to the computer. For example, one can make a directory ina computer file system:

import  os

Let us print all the methods of such models:

import os

We can print documentation as:

import os
print os.__doc__