0% found this document useful (0 votes)
127 views

Module in Python Notes

A python program consists of three main components: libraries, modules, and functions/sub-modules. A module is a .py file containing python code like definitions, variables, and classes. A package is a directory containing multiple python modules, while a library is a collection of packages. Modules allow code reusability, logical organization, and categorization of code. The key aspects in creating a module are that the file name must end with .py and modules can be imported using import or from statements.

Uploaded by

Tanishka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views

Module in Python Notes

A python program consists of three main components: libraries, modules, and functions/sub-modules. A module is a .py file containing python code like definitions, variables, and classes. A package is a directory containing multiple python modules, while a library is a collection of packages. Modules allow code reusability, logical organization, and categorization of code. The key aspects in creating a module are that the file name must end with .py and modules can be imported using import or from statements.

Uploaded by

Tanishka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Introduction to Python Module

A python program consists of three main Component:


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


statementwith .py extension
● A Python package is simply a directory of python modules.
● A library in python is collection of various packages. Conceptually there is
nodifference between package and python Library.

Advantages of Python Modules

● Putting code into modules is useful because of the ability to


import the modulefunctionality.
● Reusability: A module can be used in some other python code.
Hence it providesfacility of code reusability
● A module allows us to logically organize our python code.
● Grouping related code into a module makes the code easier to
understand and use.
● Categorization: Similar types of attributes can be placed in a single
module.

Creation of Module:

The following point must be noted before creating a module.

1. A module name should always end with .py extension


2. We will not able to import module if it does not end with .py
3. 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_s
quare
(s):
r
etur
n
s*s

1
def area_rect(l,b):
return l*b
importing Modules: There are two ways to import a module(s) :
1) Using import statement: we can import single as well as multiple modules
i. For importing Single Module
Syntax: import module name
ii. For importing Multiple modules
Syntax: import modulename1, modulename2,

modulename3

To Use function inside module

Syntax modulename.function name

2) Using from Statement: -To import some particular Function(s) from module
we will useimport 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)

To use a function inside a module you have to directly call function if you are
importing themodules 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)

Importing math module:-In order to use the various constants of


mathematics andoperations, we have to import math module in our program.
Example : import math

Commonly-used constants and functions in math module.

pi: - It is a mathematical constant, the ratio of the circumference of a circle to its


diameter(3.14159...)

For example
>>> print ("The value of pi is :", math.pi)
The value of pi is: 3.141592653589793
2
e: - It is a mathematical constant that returns e raised to the power x, where
e=2.718281.It is the base of natural logarithms. It is also called Euler's number.

For example :
>>>print("The value of e is :", math.e)
The value of e is :2.718281828459045
ceil(x): - Returns the smallest integer that is greater than or
equal to x.For example :
>>>print("ans :",math.ceil(7.3))
Output: ans :8
floor(x): - Returns the largest integer that is less than or equal to x.
>>>math.floor(-45.17)
-46
>>>math.floor (100.12)
100
pow(x,y): - It returns the value of xy, where x and y are numeric expressions.
>>> print ("ans :",
math.pow (3, 3))
Ans :27.0
>>>math.pow (2, 4)
16.0
>>>math.pow (5, 0)
1.0
sqrt(x): - Returns the square root of x.
>>> print ("Squre root of 65=:", math.sqrt (65))

Squre root of 65=:8.06225774829855


>>>math.sqrt (36)
6.0
fabs(x): - Returns the absolute value of x, represented as –
math.fabs (x)
where, x can be any numeric value.For example,
>>> print (math.fabs (500.23))
500.23
>>> print (math.fabs (-200))
200
cos(x): - Returns the cosine of x in radians.
>>>math.cos(3)
-0.9899924966004454

3
sin(x): - Returns the sine of x in radians.
>>>math.sin (3)
0.14112000806
tan(x): - Returns the tangent of x in radians.
>>>math.tan (3)
-0.1425465430742778

Random Module: - This module contains functions that are used for generating
random numbers. import statement is the first statement to be given in a program
for generating random numbers:

import random

The various functions associated with this module are as follows: -

(1) random():- It is floating point random number generator between 0.0 to


1.0. Here lower limit is inclusive where as upper limit is less than 1.0. i.e.
0<=N<1 where N is generated random number.

Example: -

>>>import random
>>>n=random.random()
>>>print(n)

0.1738135764235368

(2) randrange():- This method generates an integer between its lower and
upperargument. By default, the lower argument is 0.

Example :-
>>> import random
>>>Number=random.randrange (30)
>>>print(Number)
15

Note: - This line of code shall generate any one random integer number from
0 to 29excluding upper argument.

(3) randint () : - This method generates random integer number. Both the
given rangevalues are inclusive.

Example :-
>>> import random
>>>Number=random.randint (100,500)
>>>print(Number)
151

4
Statistical Module: - This module provides functions for calculating
mathematical staticsof numeric (real valued) data. There are 3 basic functions
under this module.

1. mean()
2. median()
3. mode()

In order to use these functions, we have to import statistics module in our code.

1. mean(): - It calculate the average of all


given numbers.Example: -
>>> import statistics
>>>L=[1,2,3,4,5,6]
>>>print(statistics.mean(L))
3.5 [Note: - 3.5 is the average of all numbers in the list]

median(): - The median is the middle number in a group of numbers. If group


has odd numbers of element then it will return the middle position value,
otherwise will return theaverage of values at mid and mid-1 position.

Example: -
>>> import statistics
>>>L=[10,20,30,40,50,60,70]
>>>print(statistics.median(L))
40

2. mode(): - The mode function returns number that occurs most often within a
set of numbers.

Example:-
>>> import statistics
>>>L=[10,5,30,5,5,60,70]
>>>print(statistics.mode(L))
5

(1 MARK QUESTIONS)

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.

5
Q2. If a,b,c=3,4,1 then what will be the value of

math.sqrt(b)*a-c

a) 5.0
b) 5
c) 2
d) 4.0
Q3. What is displayed on executing
print(math. fabs(-3.4))?
a) -3.4 b) 3.4 c) 3
d) -3
Q4. What is the file extension of python module file?
Q5. Which of the following is not an advantage of
using modules?
a) Provides a means of reuse of program code
b) Provides a means of dividing up tasks
c)Provides a means of reducing the size of the
program
d) Provides a means of testing individual parts of
the program
Q6. Which operator is used in the python to import all modules from packages?
(a) . operator (b) * operator
(c) ‐> symbol (d) , operator

Q7. In python which is the correct method to load a module math?


(a) include math (b) import math
(c) #include<math.h> (d) using math
Q8. Which is the correct command to load just the tempc method from a module
calledusable?
(a) import usable, tempc (b) Import tempc from usable
(c) from usable import tempc (d) import tempc
Q9. Which of the following can not be returned by random.randrange(4)
a) 0
b) 3
c) 2.3
d) None of the mentioned
Q10. What does random.seed(3) return?
a) True
b) None
6
c) 3
d) 1
(2 MARKS QUESTIONS)
Q1. Write two forms of import statement.
Q2. Write a python program to calculate the square root of given number n.
Q3. What is the utility of Python standard library's math module and random
module?

Q4. Define 'module' and 'package'.


Q5. Which of the following is the same as math.exp(p)? Also give the explanation.
a) e ** p b) math.e ** p
c) p ** e d) p ** math.e
Q6. List any two advantages of modules?
Q7. How is math.ceil (89.7) different from math.floor (89.7)?
(3 MARKS QUESTIONS)

Q1. Select the possible output(s) of the following code from the given option. Also,
specify the maximum and minimum value that can be assigned to variable NUM.
import random
cities = [‘Agra’, ‘Delhi’, ‘Chennai’, ‘Bhopal’]
NUM = random.randint(1,2)+1 for city in cities:
for I in range(1,NUM):
pint(city, end=‘’)print(‘\n’)
a) Agra C) Agra
DelhiDelhi Delhi
ChennaiChennaiChennai Chennai
BhopalBhopalBhopalBhopal Bhopal
b) Agra d) ChennaiChennai
Agra BhopalBhopal
DelhiDelhi

Q2.What is the utility of Python standard library's math module, random module and
statistics module?
Q3. 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 six 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
7
Case Study Based Questions
1. Write a python program that takes a number from 1 to 9 and stored inside
the variable “guess_num”. If the user guesses wrong then the prompt appears
again and the user continues to input another number repetitively until the
guess is correct. On successful guess, the user will get a “Well guessed!”
message, and the program will exit.Write a program to perform insertion
sorting on a given list of strings, on the basis of length of strings. That is, the
smallest length string should be the first string in the listand the largest
length string should be the last string in the sorted list.
Answers (1 Mark Questions)
A1 :-b) Design and implementation of specific functionality to be incorporated
into aprogram
A2. :- a) 5.0
A3. :- b) 3.4
A4. The file extension of python module file is .py
A5. Answer: c
A6. * operator.
A7. import math
A8. C) from usable import tempc
A9. C) 2.3
A10. b) None
Answers (2 Marks Questions)

A1. There are two forms of import statements:

1. import <modulename>
2. from <module> import <function>

A2.

import math
n=float(input('Enter n='))
ans=math.sqrt(n)
print('Square root of',n,' = ',ans)
A3.
(i) The math module is used for math related functions that work with all
numberexcept complex numbers.
(ii) The Random module is used for different random number generator
functions.
A4.

Each python program file is a module which imports other modules like
objects and attributes. A python program folder is a package of modules. A
package can have modulesor sub folders.
A5.

Answer: b

8
EXPLANATION: math.e is the constant defined in the math module.

9
A6. Advantages of modules are:-
1. Reusability : Working with modules makes the code reusable.
2. Simplicity: Module focuses on a small proportion of the problem,
rather than focusing onthe entire problem.

A7.
Ceil: The function 'ceil(x)' in Python returns the smallest integer not less than
x i.e., the next integer on the RHS of the number line. Hence, 'math. ceil(89.7)'
will return 90whereas 'math. floor(89.7)' will return 89.
Answers (3 Marks Questions)

A1. Options b and c are correct. Maximum and Minimum value assigned to NUM
are 3 and2 respectively.
A2.
(i) Math module: The math module is used for math-related
functions that workwith all number types except for complex
numbers.
(ii) Random module: The random module is used for different
random numbergenerator functions.
(iii) Statistics module:- The statistics module is used statistic-related
functions likemean, mode, median etc.

10
A3. Options ii, iii, v and vi are
possible outputs
Answers (Case Study based Questions)
A1.
import

random

target_nu

m,

guess_nu

m=

random.randin

t(1, 10), 0while

target_num !=

guess_num:

guess_num = int(input("Guess a number between 1 and 10 \ until you

get itright:"))print(target_num)

target_num = random.randint(1, 10)

print('Congratulation both target and guess

numbers aresame',target_num,guess_num)

print('Well guessed!')

11

You might also like