0% found this document useful (0 votes)
19 views25 pages

MODULES

The document provides an overview of Python modules, explaining their purpose, how to import them, and the use of various import statements. It covers module functionalities, namespace management, and built-in functions like dir(), globals(), and locals(). Additionally, it highlights the advantages of using modules and lists examples of standard library modules available in Python.

Uploaded by

KavithaPrasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views25 pages

MODULES

The document provides an overview of Python modules, explaining their purpose, how to import them, and the use of various import statements. It covers module functionalities, namespace management, and built-in functions like dir(), globals(), and locals(). Additionally, it highlights the advantages of using modules and lists examples of standard library modules available in Python.

Uploaded by

KavithaPrasad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

MODULES

Prepared by: Dr.M.N.Kavitha


Modules
 Modules are pre-written pieces of code that are used to
perform a particular task like generating random numbers,
perform mathematical operations, etc.
 It allows to reuse one or more functions in the program,
even in the programs where those functions are not
defined
 Every python file is a module saved with the extension .py
 We can use functions or variables defined in a module by
simply importing that particular module in our program:
Example:
Syntax: import module_name import sys
Output: print(“Python
Path:”,sys.path)
Python Path: ['', 'C:\\Program Files\\Python311\\python311.zip', 'C:\\Program Files\\Python311\\
DLLs', 'C:\\Program Files\\Python311\\Lib', 'C:\\Program Files\\Python311', 'C:\\Program Files\\
Python311\\Lib\\site-packages']
import
 A module imported in a program must be located and
loaded into memory before it can be used.
 Python searches for the modules in the current working
directory, if its not found it searches in the directories
in the PYTHONPATH environment variable, if its not
found then a python installation Lib directory is
searched; if its not located, ImportError exception is
generated.
 Once a module is located, it is loaded into memory. A
compiled version of the module with file extension .pyc is
generated.
from…import
 A module may contain definition for many variables and
functions
 Using import, we can use any variable or function in that
module
 But if selected variables or functions are needed, use
from…import statement.
Example:
 Syntax: from module_name
Output: import
variable/function_name
from math import sqrt
n=int(input(“Enter a number:”)) Enter a number:9
Square root of 9 is 3.0
print(“Square root
of”,n,”is”,sqrt(n))
Example:
Output:

from math import pi PI= 3.141592653589793


print(“PI=“,pi)
from…import
 To import more than one item from a module, use a
comma separated line:
from math import pi, sqrt

Example:
Output:
from math import pi,sqrt
Enter a number:4
n=int(input(“Enter a Square root of 4 is 2.0
number:”)) PI= 3.141592653589793
print(“Square root
of”,n,”is”,sqrt(n))
print(“PI=“,pi)
Example: Program to generate random
numbers from 1 to 10
Example: OUTPUT:

>>> import random


import random >>>
print(random.randint(1, print(random.randint(1,10))
10)) 7
>>> import random
>>>
print(random.randint(1,10))
2
>>> import random
>>>
print(random.randint(1,10))
5
>>> import random
>>>
Example: Program to generate 10
random numbers from 20 to 50
Example: OUTPUT:

33
import random 37
for i in range(10): 35
21
print(random.randint(20,50 31
)) 32
42
25
26
37
Rename a module
 We can rename the module in our code
Eg:
from math import sqrt
as s

print(s(49))

Output:

7.0
Import all names
 In Python, we can import all names(definitions) from a module using
the following construct:

Example
Output
from math import * The value of pi is
3.141592653589793
print("The value of pi is", pi)
120
print(factorial(5)) 0.9129452507276277
8.0
print(sin(20))

print(pow(2,3))
Printing Name of a module
 The module name can be displayed using the
__name__attribute of the module.
 Main modules are python files executed directly and
are given the special name __main__
Example:

print(“Welcome”)
print(“Module Output:
Name:”,__name__)
Welcome
Module Name:__main__
Printing name of the module

Mod1.py The main module may import


any number of other modules
def show(a):
print(“Hi”,a) Output:
print(“Module Name:”,__name__)
Hi Friends!
Module Name: Mod1
sample.py Module Name: __main__
import Mod1
Mod1.show(“Friends!”)
print(“Module Name:”,__name__)
dir()
 dir() is built-in function used to list the identifiers
in a module
 The identifiers can be classes, functions and
variables
 Example
import math
print(dir(math))

OUTPUT:
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh',
'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e',
'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',
'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log',
'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians',
'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
dir()
 dir() can be used with user defined modules
also
 Example import Mod1 def show():
print(dir(Mod1) print(“Hello”)
) A=10

OUTPUT:
['A', '__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'show']
math() module

OUTPUT:
4
10
120
0.912945250727
6277
2.0
8.0
calendar module

Example: OUTPUT:

import calendar
Displays the calendar for the
year 2023
print(calendar.calendar(2023))
datetime() module

Find out five functions in this module


Modules and Namespace
 A namespace is a container that provides a named context for
identifiers
 Two identifiers with the same name in the same scope will lead to a
name clash
Mod1.py sample.py
def show(a): import Mod1, Mod2
print(“Hi”,a) show(“Alex!”)

Mod2.py
In the example, Mod1 and Mod2 contains
def show(a): the show() function. When we call show()
print(a,“Welcome to Python”) from the main module, there will be a
nameclash
Modules and Namespace
 Provide a fully qualified name with the name of the
module in the main module.
sample.py
OUTPUT
Mod1.py import Mod1, Mod2
Hi Alex!
def show(a): Mod1.show(“Alex!”)
print(“Hi”,a) Mod2.show(“Alice”) Alice Welcome to Python

Mod2.py
def show(a): The name clash is resolved here using
print(a,“Welcome to Python”) fully qualified namespace
Namespace
 Built-in namespace contains names of all the built-in functions, constants, etc
 The global namespace contains the identifiers of the currently executing module
 The local namespace has identifiers defined in the currently executing function

def max(a,b): Global namespace


print(“User-defined function: max”)
large = 0 local namespace

if a>b: OUTPUT
large = a User-defined function: max
else:
Max=20
large=b
Sum=30
return large
a,b = 10, 20
print(“Max=“,max(a,b))
Built-in namespace
globals() & locals()
 globals() and locals() are used to return the names in the
global and local namespaces. The result of these functions
are dependent on the location from where they are called.
 If locals() is called from within a function, names that can be
accessed locally from that function will be returned
 If globals() is called from within a function, all the names
that can be accessed globally from that function will be
returned
 Example:
Example: globals()

Example:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__':
'E:\\pythonprograms\\add1.py', 'm': 10, 'add': <function add at
0x0000020E8840F920>, 'n': 20, 'c': 15}
reload()

The code in the module is executed once when they are


imported into a program. If we want to re-execute the
top-level code in a module, this function can be used:
Syntax: reload(modulename)
Module Private Variables
 All identifiers defined in a module are public by
default
 If we want to declare some variables or functions
as private within a module, then we should declare
these identifiers starting with two underscores(__).
Then these identifiers can be used only within the
module.
Example:
__a=10
Advantages of Modules

 They make the design modular


 Enhances reusability of services and
functionality
 It logically organizes the code making it easier
to understand and use
STANDARD LIBRARY MODULES
 Modules that are pre-installed in Python are known as
standard library
Examples:
 string
 datetime
 math
 random
 sys
 unittest
 socket
 email

You might also like