Unit-II Modules Programming Excercises 240426 180444
Unit-II Modules Programming Excercises 240426 180444
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..
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
==============================================================================================================================================================================
Python Programming Prof.B.Sreenivasu Sreyas Institute of Engineering and Technology Hyderabad Page 2 of 10
==============================================================================================================================================================================
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
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
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
add(5,9)
OUTPUT:
OUTPUT:
the subtraction of x and y is: 2
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:
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
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.
import mypack.arith
mypack.arith.add(22,10)
result=mypack.arith.sub(22,10)
print("Result of subtraction: ",result)
OUTPUT:
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()
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