Module in Python Notes
Module in Python Notes
Creation of Module:
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
2) Using from Statement: -To import some particular Function(s) from module
we will useimport statement
Function(s)>OR
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)
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))
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
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.
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)
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
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)
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
target_num !=
guess_num:
get itright:"))print(target_num)
numbers aresame',target_num,guess_num)
print('Well guessed!')
11