Docsity

Python Libraries and Modules: Understanding the Relationship, Study notes of Design

Toggle sidebar
bg1
CHAPTER4:USINGPYTHONLIBRARIES
Apythonprogramconsistofthreemaincomponents
1)Libraryorpackage
2)Module
3)Function/SubModules
RELATIONSHIPBETWEENAMODULE,PACKAGEANDLIBRARYINPYTHON
Amoduleisafilecontainingpythondefinitions,variablesandclassesandstatementwith.pyextension
APythonpackageissimplyadirectoryofpythonmodules.
Alibraryinpythoniscollectionofvariouspackages.Conceptuallythereisnodifferencebetweenpackage
andpythonLibrary.
AdvantagesofPythonModules
1) Puttingcodeintomodulesisusefulbecauseoftheabilitytoimportthemodulefunctionality.
2) Reusability: A module can be used in some other python code.Henceitprovidefacilityofcode
reusability
3) Amoduleallowsustologicallyorganizeourpythoncode.
4) Groupingrelatedcodeintoamodulemakesthecodeeasiertounderstandanduse.
5) Categorisation:Similartypesofattributescanbeplacedinasinglemodule.
CreationofModule:
Thefollowingpointmustbenotedbeforecreatingamodule
Amodulenameshouldalwaysendwith.pyextension
Wewillnotabletoimportmoduleifitdoesnotendwith.py
AmodulenamemustnotbeaPythonkeyword
Amoduleissimplyapythonfilewhichcontainsfunctions,classesandvariables
Letusconsiderthefollowingexampleofamodulenamearea.pywhichcontainsthreefunctionsname
area_circle(r),area_square(s),area_rect(l,b)
importmath
defarea_circle(r):
returnmath.pi*r*r
defarea_square(s):
returns*s
defarea_rect(l,b):
returnl*b
importingModules:
Therearetwowaystoimportamodules
1) Usingimportstatement:wecanimportsingleaswellasmultiplemodules
1.1 ForimportingSinglemodule
Syntax: importmodulename
1.2 ForimportingMultiplemodules
Syntax:importmodulename1,modulename2,modulename3
ToUsefunctioninsidemodule
Syntax modulename.functionname
2)UsingfromStatement:ToimportsomeparticularFunction(s)frommodulewewilluseimport
statement
2.1ToimportParticularFunction
Syntax:From<modulename>import<writenameofFunction(s)>
OR
From<modulename>import*
(Thisstatementwillimportallthefunctionsfrommodules)
pf3
pf4
pf5

Partial preview of the text

Download Python Libraries and Modules: Understanding the Relationship and more Study notes Design in PDF only on Docsity!

CHAPTER 4: USING PYTHON LIBRARIES

A python program consist of three main components 1)Library or package 2)Module 3)Function/Sub Modules

RELATIONSHIP BETWEEN A MODULE, PACKAGE AND LIBRARY IN PYTHON

A module is a file containing python definitions, variables and classes and statement with .py extension A Python package is simply a directory of python modules. A library in python is collection of various packages. Conceptually there is no difference between package and python Library.

Advantages of Python Modules

  1. Putting code into modules is useful because of the ability to import the module functionality.
  2. Reusability: A module can be used in some other python code. Hence it provide facility of code reusability
  3. A module allows us to logically organize our python code.
  4. Grouping related code into a module makes the code easier to understand and use.
  5. Categorisation: Similar types of attributes can be placed in a single module.

Creation of Module :

The following point must be noted before creating a module  A module name should always end with .py extension  We will not able to import module if it does not end with .py  A module name must not be a Python keyword A module is simply a python file which contains functions, classes and variables

Let us consider the following example of a module name area.py which contains three functions name area_circle(r),area_square(s),area_rect(l,b)

import math def area_circle(r): return math.pirr def area_square(s): return ss def area_rect(l,b): return lb

importing Modules:

There are two ways to import a modules

  1. Using import statement: we can import single as well as multiple modules 1.1 For importing Single module Syntax: import modulename

1.2 For importing Multiple modules Syntax: import modulename1, modulename2, modulename To Use function inside module Syntax modulename.function name

  1. Using from Statement :To import some particular Function(s) from module we will use import statement 2.1 To import Particular Function Syntax: From import OR From import * (This statement will import all the functions from modules)

To use a function inside a module you have to directly call function if your are importing the modules using from statement Example : Let us consider the following code.In this program we import the module with the help of from statement and directly use the function instead of specifying Module name

from area.py import area_rect area_rect(5,4)

Alias name of Module :

providing another name to module is known as alias name. When we provide an alias name ,then alias name is used for calling function Syntax: import modulename as example import area as A

now we will call function area_circle using alias name A of module area like as A.area_circle(5)

Note : we can also provide alias name to function of modules whenever we are using it with python from statement and whenever we have to call any statement then we have to provide function alias name instead of function original name ‘ Example: from area import area_Circle as C C(6) # C is the alias name of function area_circle of module area

CREATION OF LIBRARY/PACKAGE

Steps to create and import the package

  1. Create a directory named XYZ and add all the modules in the directory XYZ Import os.mkdir(“XYZ”
  2. Create a file init.py in the directory XYZ. init.py file is used to make a directory as package.This file is used to initialse the package
  3. Import the package named XYZ and use the attributes in some other program

Locating Modules Python interpreter searches for module in the following sequences

SECTION A (1 MARK QUESTION) Q1. Which of these definitions correctly describe a module? a) Denoted by triple quotes for providing the specifications of certain program elements. b) Design and implementation of specific functionality to be incorporated into a program c) Defines the specifications of how it is to be used. d) Any program that reuses code.

Q2. Which of the following is not true about main modules? a) When a python file is directly executed ,it is considered main module of a program b) Main modules may import any number of modules c) Special name given to main modules is: main d) Other main modules can import main modules

Q3. Which of the following is not a valid namespace? a) global namespace b) public namespace c) built in namespace d) local namespace

Q4. Which of the following is false about “import module name” form of import? a) The namespace of imported module becomes part of importing module b) This form of input prevents name clash c) The namespace of imported module becomes available to importing module d) The identifiers in module are accessed as: modulename.identifier

Current directory

Each directory in shells variable PYTHONPATH

Checks default path where python is installed

not found (^) not found

Q3. What happens when python encounters an import statement in a program? What would happen, if there is one more important statement for the same module, already imported in the same program?

Q4. What is the problem in the following piece of code? from math import factorial print (math.factorial (5))

Q5. What is the output of the following piece of code? #mod def change (a): b=[x2 for x in a] print (b) #mod 2 def change (a): b=[xx for x in a] print (b) from mod 1 import change from mod 2 imoprt change #main S=[1,2,3] Changes(s)

Q6. What would be the output produced by the following code : import math import random print ( math.ceil (random.random())) Justify your answer.

SECTION C (3 MARK QUESTION) Q1. Observe the following code and answer the question based on it.

the math_operation module

deff add (a,b): return a+b def subtract(a,b): return a‐b

Fill in the blanks for the following code:

  1. Math _operation #get the name of the module.
  2. print (_______) #output:math_operation

    Add 1and 2

  3. print(_______(1,2) ) # output 3

Q2. Consinder the code given in above and on the basis of it, complete the code given below:

import the subtract function

#from the math_operation module 1.________________________ #subtract 1from 2 2.print(_______(2,1) ) # output : 1

Import everything from math____operations

3._______________________________ print (subtract (2,1) ) # output: print (add (1,1) ) # output:

Q3. Consider a module ‘simple’ given below: #module simple.py “ “ “Greets or scold on call” “ “ def greet(): “ “ “ Greet anyone you like :‐)” “ “ Print (“Helloz”) def scold (): “ “ “ Use me for scolding ,but scolding is not good:‐( “ “ “

Print (“Get lost”) Count = Print (“greeting or scolding‐ is it simple?”) Another program ‘test.py’ imports this module.The code inside test.py is : #test.py import simple print(simple.count) What would be the output produced ,if we run the program test.py? justify your answer.

Q4. Consider the following code: import math import random print(str(int(math.pow( random.randint (2,4),2) )), end = ‘ ’) print(str( int ( math.pow(random.randint(2,4), 2))) , end = ‘ ’) print( str ( int (math.pow( random .randint (2,4),2))))

What would be possible outputs out of the given four choices? (i) 2 3 4 (ii) 9 4 4 (iii) 16 16 16 (iv) 2 4 9 (v) 4 9 4 (vi) 4 4 4 ANSWERS SECTION A (1 MARK ANSWERS ) Ans 1. b) Design and implementation of specific functionality to be incorporated into a program Ans 2. d) Ans3, b) Ans 4. a) Ans5. b) Ans6. c) Ans 7. (b) Ans 8. (c ) Ans 9. (b) Ans 10. (C) Ans 11. (d) SECTION B (2 MARK ANSWERS ) Ans 1. Pythonpath command is used for the same. It has a role similar to path.This variable tells the python interpreter where to locate the module files imported into a program.It should include the python source library ,directory containing python source code.

Ans 2. (d)

Ans 3. When python encounters an important statement,it does the following:  The code of imported module is interpreted and executed.  Defined functions and variables created in the module are now available to the program that imported module.  For imported module, a new namespace is set up with the same name as that of the module. Any duplicate import statement for the same module in the same program is ignored by python

Ans 4. In the “from–import” from of import, the imported identifiers (in this case factorial()) become part of the current local namespace and hence their module’s name aren’t specified along with the module name. Thus, the statement should be: print( factorial (5) )

Ans 5. There is a name clash. A name clash is a situation when two different entities with the same name become part of the same scope. Since both the modules have the same function name, there is a name clash, which is an error..

Ans6. The output Produced would be 1.