0% found this document useful (0 votes)
30 views10 pages

Unit-II Modules Programming Excercises 240426 180444

This file has modules in python

Uploaded by

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

Unit-II Modules Programming Excercises 240426 180444

This file has modules in python

Uploaded by

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

Department of Computer Science and Engineering (Artificial Intelligence & Machine Learning)

Python Programming – II Year B.Tech II Semester


Course Instructor: Prof.B.Sreenivasu, 9502251564, 9550411738
=============================================================================================================
Modules: Importing Modules, Importing Module Attributes, Module Built-in Functions, Packages.
=============================================================================================================

Introduction:

➢ So far, We have developed several python programs. These python programs can
be called “modules” if they can be imported and used by other python programs.
➢ A module is a python program that can be imported into other programs and can
be used in other programs.
➢ Since module is a python program, it may contain classes, objects, functions
(Methods) etc.
➢ Module is Python file containing collection of functions, classes, objects etc..

Note: Naming a Module


You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module:
You can create an alias when you import a module, by using the as keyword
---------------------------------------------------------------------------------------------------------------------------------
#How do you make a module? Give an example of construction of a module using
different
#geometrical shapes and operations on them as its functions
# name of python program geometry.py
def square_area(s):
area=s*s
return area

def square_perimeter(s):
perimeter=4*s
return perimeter

def rectangle_area(l,b):

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 1 of 10
area=l*b
return area

def rectangle_perimeter(l,b):
perimeter=2*(l+b)
return perimeter
----------------------------------------------------------------------------------------------------------------------------------
Example python program where above python program geometry.py is imported
import geometry
s=int(input("enter side of a square: "))
l=int(input("enter length of a rectangle: "))
b=int(input("enter breadth of a rectangle: "))
res=geometryB.square_area(s)
print("area of square: ",res)
res1=geometryB.square_perimeter(s)
print("perimeter of square: ",res1)
res2=geometryB.rectangle_area(l,b)
print("area of rectangle: ",res2)
res3=geometryB.rectangle_perimeter(l,b)
print("perimeter of rectangle: ",res3)
----------------------------------------------------------------------------------------------------------------------------------

Programming Exercises:

#python program to create a user defined module called arith.py with three functions
#this module name is arith.py
#this module contains three functions

def add(x,y):
z=x+y
print("the sum of two numbers is: ",z)

def mul(x,y):
z=x*y
return z

def sub(x,y):
z=x-y
return z
==============================================================================================================================================================================

❖ a package is a folder or directory that contains some modules

❖ a group of packages is called software library

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 2 of 10
==============================================================================================================================================================================

Different ways of writing import statement


❖ import arith
▪ when we write module name in the import statement as shown. PVM(python virtual
machine) will add this module name before every python object in our program. i.e
use.py that means if we have the add() function in our program, PVM will make it
arith.add() internally, hence, we should call the add() function in our program as
arith.add() or arith.sub() or arith.mul()
❖ import arith as ar
▪ Here ar is another name for arith or alias name for the ‘arith’ module. When an alias
name is used like this, PVM will add the alias name before the python object in the
program. Hence we must call the function using the alias name as ar.add() or ar.sub()
❖ from arith import*
▪ Here ’*’ represents ‘all’. In this case, PVM does not bring the module name ‘arith’ into
our program. Instead ,it brings all the functions inside the arith module into our
program. That means functions add(), sub() and mul() are available directly in our
program. Hence, we can refer to those functions directly as add() or sub() or mul()
❖ from arith import add, sub
▪ Here, we are specifically mentioning the names of the functions add and sub. In this
case, PVM brings the functions add() and sub() from arith module directly into our
program. Therefore we can call them directly as add() or sub()

# a python program to import and use arith.py module in use.py program

import arith

arith.mul(3,9)
res=arith.mul(3,9)
print("Multiplication of two numbers is: ",res)

arith.add(45,89)

OUTPUT:
Multiplication of two numbers is: 27
the sum of two numbers is: 134

# a python program to import arith.py module as ar


# You can create an alias when you import a module, by using the as keyword
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 3 of 10
import arith as ar

ar.add(5,9)
ar.mul(6,9)
res=ar.mul(6,9)
print(res)
ar.sub(134,98)
result=ar.sub(134,98)
print(result)

OUTPUT:
the sum of two numbers is: 14
54
36

----------------------------------------------------------------------------------------------------------------------------
Module Attributes:
Python Module Attributes:
Python Module Attributes:
➢ name
➢ doc
➢ file
➢ dict
❖ Python module has its attributes that describes it.
❖ Attributes perform some tasks or contain some information about the module.
Some of the important attributes are explained below:
1. __name__ Attribute
The __name__ attribute returns the name of the module.
By default, the name of the file (excluding the extension .py) is the value of __name__attribute.
Example: __name__ Attribute
import math
print(math.__name__)

Output:
Math

Example: __name__ Attribute


import sys
print(sys.__name__)

Output:
sys

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 4 of 10
Key Note: However, this can be modified by assigning different strings to this attribute.
Change hello.py as shown below.
Example: Set __name__
def SayHello(name):
print (f’{} how are you’)
__name__="SayHello"
And check the __name__ attribute now.
Example: Set __name__
import hello
print(hello.__name__)

Output:
SayHello
Note: The value of the __name__ attribute is __main__ on the Python interactive shell and in
the main.py module.
Example: __main__
print(__name__)
When we run any Python script (i.e. a module), its __name__ attribute is also set to __main__.
For example, create the following welcome.py in IDLE.
Example: welcome.py
print("__name__ = ", __name__)
Run the above welcome.py in IDLE. You will see the following result.
Output in IDLE:
__name__ = __main__

Note: However, when this module is imported, its __name__ is set to its filename.
Now, import the welcome module in the new python program (python file) test.py with the
following content.
Example: test.py
import welcome
print("__name__ = ", __name__)
Now run the test.py in IDLE. The __name__ attribute is now "welcome".
Example: test.py
_name__ = welcome
This attribute allows a Python script to be used as an executable or as a module.
2.__doc__ Attribute
❖ The __doc__ attribute denotes the documentation string (docstring) line written in a
module code.
Example:
import math
print(math.__doc__)

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 5 of 10
Consider the following python script is saved as greet.py module.
greet.py
"""This is docstring of test module"""
def SayHello(name):
print(f’Hi{} how are you’)
return
The __doc__ attribute will return a string defined at the beginning of the module code.
Example: __doc__
import greet
print(greet.__doc__)

3.__file__ Attribute
➢ __file__ is an optional attribute which holds the name and path of the module file from
which it is loaded.
Example: __file__ Attribute
import io
print(io.__file__)
Output:
'C:\\python37\\lib\\io.py'

4.__dict__ Attribute
The __dict__ attribute will return a dictionary object of module attributes, functions and other
definitions and their respective values.
Example: __dict__ Attribute
import math
print(math.__dict__)
Key note:
 The dir() is a built-in function that also returns the list of all attributes and functions in a
module.
Example: dir()
import math
print(dir(math))
----------------------------------------------------------------------------------------------------------------------------------
# Python program that can read values of python module attributes

import sys
print(sys.__name__) # module attribute __name__ rerturns name of the module
print(sys.__doc__) # represents documentation string (doc string) of a module

----------------------------------------------------------------------------------------------------------------------------------

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 6 of 10
# write a python program to read values of module attributes ( for example python module :sys
import sys
print(sys.__name__) # name attribute of module returns name of the module
print(sys.__doc__) # returns documentations string of a particular pythpon module
----------------------------------------------------------------------------------------------------------------------------
# write a python program to read values of module attributes ( for example python module: math
import math
print(math.__name__) # name attribute of module returns name of the module
print(math.__doc__) # returns documentations string of a particular python module

OUTPUT:
math
This module provides access to the mathematical functions
defined by the C standard.
----------------------------------------------------------------------------------------------------------------------------
# a python program to import and use arith.py module

from arith import*

add(5,9)

OUTPUT:

the sum of two numbers is: 14

# a python program to import and use arith.py module

from arith import add,sub


sub(9,7)
res=sub(9,7)
print("the subtraction of x and y is: ",res)

OUTPUT:
the subtraction of x and y is: 2

# a python program to import and use arith.py module


from arith import*

add(5,9)
mul(6,9)
res=mul(6,9)
print(res)
sub(134,98)
result=sub(134,98)
print(result)

OUTPUT:
the sum of two numbers is: 14
54
36

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 7 of 10
# a python program to create/define a user defined class called student

# a class is created with keyword class and then writing the class name
# __init__(self) is a special method to initialize variables

class student:

#this is an special method called constructor


def __init__(self): # this is a special method => to delcare and initialize the variables
#self.id=501
self.id=int(input("Enter student roll no: "))
#self.name="java"
self.name=input("Enter student name: ")
#self.marks=75
self.marks=int(input("Enter student marks: "))

# this is an instance(object) method


def talk(self): # to display student details
print("Hi my roll number: ",self.id)
print("Hi my name: ",self.name)
print("Hi my sub marks: ",self.marks)

#creating instance (object) to the student class


s1=student()

# call the method using the instance(object)


s1.talk()

OUTPUT:
Enter student roll no: 501
Enter student name: SNIGDHA
Enter student marks: 65
Hi my roll number: 501
Hi my name: SNIGDHA
Hi my sub marks: 65

Note: Example: student attributes => name, roll number, marks

Packages:
• A package is a folder or directory that contains some modules.
• How PVM distinguishes a normal folder from a package folder is the question.
• To differentiate the package folder, we need to create an empty file by the name
‘__init__.py’ inside the package folder.
• First of all, we should create a folder by the name ‘mypack’. For this purpose, right
click the mouse ➔ New➔Folder. Then it will create a new folder by the name ‘New
folder’ rename it as ‘mypack’.
• The next step is to create ‘__init__.py’ file as an empty file inside ‘mypack’ folder.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 8 of 10
• First , go to the mypack folder by double clicking on it. Then right click the mouse➔
New➔Text Document. This will open a Notepad file by the name ‘New Text
Document.txt’. double click on this file to open it. Then File➔Save as➔ Type the file
name in double quotes as “__init__.py”.
• Now we can see a new file by the name ‘__init__.py’ with 0 KB size created in the
mypack folder. Store the ‘arith.py’ program into this mypack folder.
• Now mypack is treated as a package with arith.py as a module.

#a python program showing how to use a module belonging to a package ➔ mypack

#using the arith.py module of mypack package

import mypack.arith
mypack.arith.add(22,10)
result=mypack.arith.sub(22,10)
print("Result of subtraction: ",result)

OUTPUT:

the sum of two numbers is: 32


Result of subtraction: 12

Note:
• Observe the import statement in the beginning of the above program
• import mypack.arith
• it represents that mypack is the package (or folder) in which the arith module is found.
• This arith module is imported.
• When we import like this, we need to add the package name and module name before the functions
or classes that are defined inside the module as mypack.arith.add()

The following are the different ways of writing import statement


❖ import mypack.arith as ar
 Then refer to the functions as: ar.add() or ar.sub()
❖ from mypack.arith import*
❖ from mypack.arith import add,sub,mul
 in the above two cases, we can directly all the functions as add() or sub() or mul()
Libraries:
• we can extend the concept of packages to form libraries.
• A group of packages is called a “software library”

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 9 of 10
• A library contains several packages and each package contains one or more
modules. each module contains useful classes and functions.

Points to remember:
➢ A module is a python program that can be imported and used in any other python program.
➢ A group of modules is called a package
➢ A group of packages form a software library
➢ We can create user defiled modules.
➢ A module contains group of classes, functions and variables
➢ A function is similar to a program that consists of a group of statements which performs a task.
➢ A function is created / defined / developed using keyword def
def functionname(parameter1,parameter2,…)
➢ a function is executed only when it is called using its name.
➢ a function without name is called ‘anonymous function’ or lambda function.

Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 10 of 10

You might also like