Modules

Modules are Python's way of organizing its code. There are many functions made by Python developers that are available for you to use in any Python program, and related functions are grouped into modules. In other words, a module is a file (or a group of files) containing Python definitions and statements. A module can define functions, classes and variables and many other things.

import statement

When you use a module, like when you need to access the functions or variables defined in it, you'll need to import that file into your current program with a statement like this:

import moduleName

Whenever you see import in a program, you know it is bringing in code from somewhere else.

Dot Notation

After importing a module, we can then access the items, or attributes, in that module in this format:

module.item

The dot operator, or a period (.) in regular English, is used to access an item inside a module as well as other types of objects.

You can think of this format as similar to lastname.firstname, where the lastname is the module family and the firstname is the individual entry in the module.

math module

Python comes with a library of standard modules. The math module is one of them. It allows you to access many useful mathematical functions.

Let's look at some functions we are familiar with. First, we import the math module and access its attributes using math.item.

import math       

print(math.pi)             # 3.141592...(the mathematical constant π)

print(math.sqrt(100))      # 10 (the square root of 100)

print(math.factorial(4))   # 24 (4 factorial, 4*3*2*1)

print(math.pow(2, 5))      # 32 (2 raised to the power 5)

from ... import ...

Instead of importing the whole module, we can import specific items from a module into the current program:

from module import item

Then the item can be accessed directly without dot notation. If you only need one or two items from a module, this might save you some typing when using them.

For example, if you only need sqrt (square root) from math:

from math import sqrt

# access sqrt directly without typing "math" each time
print(sqrt(25))         # 5

results matching ""

    No results matching ""