Module

Modules are Python's solution to manage code, Python comes with many built-in functions. Related functions are saved in files known as modules. In other words, A module is a file containing Python definitions and statements. A module can define functions, classes and variables. A module can also include runnable code.

A very simple module can be a file with a .py extension that contains functions and variables. The functions, classes, variables in a module are called attributes of a module.

import statement

In order to use the module, (i.e. use the functions or variables in it), We import that file into our current program by specifying

import moduleName

Whenever you see import in a program, you know the programmer is bringing in code from elsewhere.

Dot Notation

After import a module, we can then access the items(attributes) in that module with the ' . ' (dot operator), providing the module name and the attributes' name joined together with a “dot” like:

moduleName.itemName

You can think of this as 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, math module is always available, it provides access to many mathematical functions.

Let's look at some functions we are familiar with. First, we import math module, then access it's attributes using math.itemName

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)

((keep??

# demo math.pow(t,s) in CodeCraft, t**s
t = 4
s = 2

column(2, -20, t, 'wool_blue')    
for j in range(s):
    block(2, (t+2+j*2), -20, 'obsidian')  # s blocks on top of column t indicating the power

column(4, -20, math.pow(t,s), 'wool_red')   # the red column has height t**s, that is 16

))

from ... import... statement

Other than import the whole module, we can import specific attributes from a module into the current namespace.

from modName import attributeName

then the attribute is accessed directly without dot notation. This way of import save you a lot of typing.

Such as previous math module, we can do:

from math import sqrt

# access sqrt directly
print( sqrt(25) )         # 5

results matching ""

    No results matching ""