Python3 Modules

Python  Modules

Modules :

             Modules refer to a file containing Python statements and definitions.
   A file containing Python code, for eg: abc.py, is called a module and its module name would be "abc"

  We use module to break down a large programs into simpler manageable and organized files. Furthermore, module provide reusability of code.

  We can define our most used functions in a module  and import it, instead of copying their definitions into different programs.

How to import a module?

 We use the import keyword to do this.

       import example     #imported example module

  Using the module name we can access the function using dot( . ) operation.

       example.add(10,10)

output:  20

Python has a lot of standard modules available.

Example:

       import math
       print(math.pi)

output: 3.141592653589793

       import datetime
       datetime.datetime.now( )

output: datetime.datetime(2020,10,18,47,20,606228)

import with renaming

       import math as m
       print(m.pi)

output:   3.141592653589793

from....import statement

      We can import specific names from a module without importing the module as a whole.

       from datetime import datetime
       datetime.now( )

output:  datetime.datetime(2020,10,18,20,47,38,17242)
 
import all names

       from math import *
       print("value of PI is"+str((pi))

output:   value of PI is 3.141592653589793

 dir() built in function :

 We can use the dir() function to find out names that are defined inside a module.

       dir(example)

output:  ['__builtins__',
               '__ cached__',
               '__doc__',
               '__file__',
               '__loader__',
               '__name__',
               '__package__',
               '__spec__','
               'add']

       print(example.add.__doc__)

 output:  This program adds two numbers and return the result












Comments

Popular posts from this blog

Python3 Function Arguments

Python3 File Handling

Python3