How do Python modules work?

PythonServer Side ProgrammingProgramming

Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

When you import a module, say `hello`, the interpreter searches for a file named hello.py in the directory containing the input script and then in the list of directories specified by the environment variable PYTHONPATH.

Create a file called fibonacci.py and enter the following code in it:

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()
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 result

Now open your terminal and use cd command to change to the directory containing this file and open the Python shell. Enter the following statements:

>>> import fibonacci
>>> fibonacci.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibonacci.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

You imported the module and used its functions.

raja
Published on 19-Dec-2017 15:32:13
Advertisements