Python Modules
Modules
A module is a file containing Python definitions and statements. The file name is the module name with
the suffix .py appended.
Let's understand this by taking example,
We will write module for fibonacci Series.Let's understand this by taking example,
def fib(n): # write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return resultYou can import this like:-
import fibo Use like this
>>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. Or you can import specific method or class from module as:-
from fibo import fib
Or another variation of this is import all using * except beginning with _ as
from fibo import *
If the module name is followed by as, then the name following as is bound directly to the imported module.
import fibo as fib
>>> fib.fib(10) 1, 1, 2, 3, 5, 8
There are standard modules like
- sys
- os
- re
- random
- math
Comments
Post a Comment