CBSE CS

cbse cs logo

Home

Library and Modules in Python

Module

A module is a file (.py) containing Python definitions (i.e. functions) and statements.

Standard library of Python is extended as module(s) to a programmer.

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application. Definitions from the module can be used within the code of a program.

How to use Module

To use these modules in the program, we need to import the module. Once you import a module, you can reference (use), any of its functions or variables in your code.

There are many ways to import a module.

import

to import full module (file).

example:
import math 

import random

from

To import all or selected functions from the module.

example :

from math import sqrt

How to use import 

import

It is simplest and most common way to use modules in our code.

Its syntax is:

     import modulename1 [,modulename2, ———]

Example

>>> import math    ( to imort math module for fuctions like sqrt)

On execution of this statement, Python will

(i) search for the file “math.py‟.

(ii) Create space where modules definition & variable will be created,

(iii) then execute the statements in the module.

How to use function

Now the definitions of the module will become part of the code in which the module was imported.

To use/ access/invoke a function, you will specify the module name and name of the function- separated by dot (.).

This format is also known as dot notation.

Example

>>> value= math.sqrt (25) # dot notation

Libraries in syllabus 

  • random

  • statistics

  • math

  • pickle

  • csv

  • mysql.connector

math Library

The math module is a standard module in Python and is always available. To use mathematical functions under this module, we have to import the module using import math statement.

How to use math function

import math
math.sqrt(4)

or

from math import *

math.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 

 ———————————————————————————

math.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

 

 ————————————————–

 

math.sqrt()

The math.sqrt() method returns the square root of a given number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772

————————————————–

The ceil()

The ceil()  function approximates the given number to the smallest integer,
greater than or equal to the given floating point number. The floor()
function returns the largest integer less than or equal to the given number.
>>>math.ceil(4.5867)
5
>>>math.floor(4.5687)
4

math.pow()

The math.pow() method receives two float arguments, raises the first to
the second and returns the result. In other words, pow(2,3) is equivalent to
2**3.
>>>math.pow(2,4)
16.0

 

The math module contains functions for calculating various trigonometric ratios for a given angle. The functions (sin, cos, tan, etc.) need the angle in radians as an argument.

 

cos (x)

It returns the cosine of x in radians, where x is a numeric expression

>>> math.cos(3)

-0.9899924966

>>> math.cos(0)

1.0

 

sin (x)

It returns the sine of x, in radians, where x must be a numeric value.

>>> math.sin(-3)

-0.14112000806

>>> math.sin(0)

0.0

 

 

tan (x)

It returns the tangent of x in radians, where x must be a numeric value.

>>>math.tan(-3)

0.142546543074

>>>math.tan(0)

0.0

 

 

degrees (x)

It converts angle x from radians to degrees, where x must be a numeric value.

>>>math.degrees(3)

171.887338539

>>>math.degrees(-3)

-171.887338539

 

 

radians(x)

It converts angle x from degrees to radians, where x must be a numeric value.

math.radians(3)

0.0523598775598

math.radians(-3)

-0.0523598775598

 

 

 

Random Module
The random module provides access to functions that support many operations. Perhaps the most important thing is that it allows us to generate random numbers. 


random.randint()
Randint accepts two parameters: a lowest and a highest number. 

It returns a int x  between a & b such that a ≤ x ≤ b

>>> random.randint (1,10)

5

>>> random.randint (-2,20)

-1

import random
print (random.randint(0, 5))
This will output either 1, 2, 3, 4 or 5.




random.random()
Genereate random number from 0 to less than 1. If we want a larger number, we can multiply it.

It returns a random float x, such that 0 ≤ x<1

>>>random.random ( )

0.281954791393

>>>random.random ( )

0.309090465205

import random
print(random.random() * 100)





randrange()
It generate random numbers from a specified range and also allowing rooms for steps to be included.  

Syntax :
random.randrange( start(opt), stop, step(opt) )

It returns a random item from the given range

>>>random.randrange(100 ,1000, 3 )

150





uniform (a,b)
It returns a floating point number x, such that a <= x < b

>>>random.uniform (5, 10)

5.52615217015

Python Random functions Questions:

Q1. Consider the code given below:

import random
r = random.randrange (100, 999, 5)
print(r, end = ‘ ‘)
r = random.randrange(100, 999, 5)
print(r, end = ‘ ‘)
r = random.randrange (100, 999, 5)
print(r)
Which of the following are the possible outcomes of the above code? Also, what can be the maximum and minimum number generated by line 2?
(a) 655, 705, 220                   (b) 380, 382, 505                  (c) 100, 500, 999      (d) 345, 650, 110


Answer

option : (a) & (d)

 

 

 

Q2. Consider the code given below:

import random
r = random.randint (10, 100) – 10
print(r, end = ‘ ‘)
r = random.randint (10, 100) – 10
print(r, end = ‘ ‘)
r = random.randint (10, 100) – 10
print(r)
Which of the following are the possible outcomes of the above code? Also, what can be the maximum and minimum number generated by line 2?
(a) 12 45 22                (b) 100 80 84                        (c) 101 12 43                        (d) 100 12 10

 

Ans : (a)

 

 

 

Q3. Consider the code given below:

import random
r= random.random() * 10
print(r, end = ‘ ‘)
r = random.random() * 10
print(r, end =’ ‘)
r = random.random() * 10
print(r)
Which of the following are the possible outcomes of the above code? Also, what can be the maximum and minimum number generated by line 2?
(a) 0.5 1.6 9.8                         (b) 10.0  1.0  0.0                   (c) 0.0  5.6  8.7          (d) 0.0  7.9  10.0

 

 

Ans : (a) & (c)

 

 

 

Q4. Consider the code given below:

import statistics as st
v = [7, 8, 8, 11, 7, 7]
m1 = st.mean(v)
m2 = st.mode(v)
m3 = st.median(v)
print(m1, m2, m3)
Which of the following is the correct output of the above code?
(a) 7 8 7.5                    (b) 8 7 7                     (c) 8 7 7.5                              (d) 8.5 7 7.5

Ans : (c)

 

 

 

 

 

Q5. What possible output(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also, specify the maximum values that can be assigned to each of the variable Lower and Upper

import random

AR = [20, 30, 40, 50, 60, 70]

Lower = random.randint(1,3)

Upper= random.randint(2,4)

for K in range (Lower, Upper+1):

    print(AR[K], end=”#”)

Output Options:

(a) 10#40#70#                       (b) 30#40#50#                      (c) 50#60#70#                      (d) 40#50#70#

 

Ans : (b), Minimum value of Lower: 3, Maximum value of Upper: 4

 

 

Q6. What possible output(s) are excepted to be displayed on the screen after executing the following code?

import  random

Lst=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

first= random.randrange(2,5)

second = random.randrange(1,3)

for L in range (second, first):

         print(Lst[L], end = “@”)

Output Options:

(a) 1@2@3@             (2) 0@1@2@3@                 (c) 2@3@                  (d) 2@3@4@

 

Ans: (a) & (c)

 

 

 

Q7. What is possible output(s) is/are expected to be displayed on screen after execution of the following program?

import random

Guess=65

for a in range(0,1):

   for b in range (1,5):

       New =  Guess+random.randrange(0,b)

       print(chr(New), end= ‘ ’)

(a) A   B   B  C                        (b) A  C  B  A                        (c) B  C  D  A (d) C  A  B  D

 

Ans: (a)

 

 

 

 

Q8. What is possible output(s) is/are expected to be displayed on screen after execution of the following program?

import random

MIN= 25

SCORE=5

for  i in range(1,5):

          Num=MIN+random.randrange(0,SCORE)

          print(Num, end = “&”)

          SCORE -=1

Output Options:

(a) 29&26&28&27&     (b) 25&26&27&28&      (c) 29&25&27&25&     (d) 25&26&25&26&

 

Ans: (c) & (d)

 

 

 

Q9. What possible output(s) is/are expected to be displayed on screen at the time of execution of the program from the following code? Also specify the maximum values that can be assigned to the variables X and Y.

import random

X = random.randrange(0,3)+2

Y = random.randrange(1,3)+2

for i in range(X):

      print(“#”, end= “”)

print(“-“, end=” “)

for i in range(Y):

           print(“@”, end=””)

Output Options:

(a) ##-@@@              (b) ###-@                  (c) ######-@@@               (d) ###-@@@@

 

Ans:   (d), Maximum value for is X: 4, , Manimum value for is Y: 4,

 

 

Q10. What possible output(s) is/are expected to be displayed on screen at the time of execution of the program from the following code? Also specify the maximum values that can be assigned to a variable val, in each iteration.

import random

msg = “VIRTUAL”

index = len(msg)-1

while msg[index] != ‘R’:

        val = random.randrange(2,index)

        print(msg[val]+”#”,end=””)

        index = index-1

(a) A#R#U#R#           (b) A#R#T#T#          (c) U#A#R#R#                     (d) U#R#T#R#

Ans : (d) , Max value=5

 

 

Q11. What possible output(s) are expected to be display execution of the following code?

import random

HIGH = 20

NUM = 15

for i in range(1,5):

      N = HIGH+random.randint(11, NUM)

      print(N, end = “:”)

     NUM – = 1

Outputs:

(a) 35:31:34:32:         (b) 35:34:33:32:                   (c)33:34:33:32:        (d) 32:31:35:31:

 

Ans: (b)

 

 

 

 

Q12. What possible output(s) are expected to be displayed on one of the execution of the following code is specify the maximum and minimum values which can be assigned to the ‘Target’ by randrange() function of random module.

import random

X= [11000, 999,99, 9]

Target = random.randrange(0,4)

for i in range(Target):

      print(X[i], “#”)

(a) 1000#

999#

99#

(b) 999#

99#

9#

(c) 1000#

1000#

999#

(d) 999#

99#

Ans: (a)     , Maximum:3 , Minimum : 0

 

 

 

Q13. From the following Python code shown, below, find out the possible output(s) from the suggested options.

import random

def week_days():

     days=[“Mon”, “Tue”, “Wed”, “Thu”, “Fri”]

    v = random.randrange(len(days)-1)

    for i in range(v,0,-1):

          print(days[i],  “-“, i+1)

week_days()

(a) Thu- 4

Wed-3

Tue-2

(b) Wed-3

Tue-2

(c) Wed -3

Tue-2

Mon-1

(d) Fri-5

Thu-4

 

Ans : (a) & (b)

 

 

 

Q14.  What possible output(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also, specify the maximum values that can be assigned to both the variables Beg and End.

import random

score= [11, 22, 33, 44, 55]

Beg = random.randrange(3)

End = random.randint(2,3)

for C in range(Beg, End):

       print(Score[C],’#’)

(a) 11#

22#

33#

(b) 22#

33#

44#

(c) 22#

33#

(d) 33#

44#

Ans:  (a), (c) Max value to a variable Beg: 2, Min value to a variable End: 3

 

 

 

Q15.   What possible output(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also, specify the first and last values that can be assigned to a the variables val in the last iteration.

import random

msg= “Luck”

x=1

for a in msg:

      val=random.randint(0, len(msg)-x)

      print(mag[val]+ “:”, end= “”)

      x=x+1

(a)           c : k : u : k :                  (b) k : u : c : c :         (c) l : u : u: c :           (d) l : c : u : l :

 

 

 

Q16. What possible output(s) is/are expected to be displayed on screen at the time of execution of the program from the following code? Also, specify the maximum values that can be assigned to the variables ‘high’.

import random

Ar=[11, 22, 33, 44, 55, 66 ]

low=random.randint(1,3)

high=random.randint(2,4)

for c in range(low, high+1):

         print(Ar[c], end= “:”)

(a)           11 : 22 : 33 :                 (b) 22 : 33 :               (c) 11 : 22:                 (d) 44 : 55 : 66 :

 

 

 

Q17. What possible output(s) is/are expected to be displayed on screen at the time of execution of the program from the following code?

from random import randint

Vibgyor=[[‘V’, ‘Violet’], [‘I’, ‘Indgo’], [‘B’, ‘Blue’], [‘G’, ‘Green’],[‘Y’, ‘Yellow’],[‘O’, ‘Orange’],[‘R’, ‘Red’]]

for i in range(3):

        first=randint(0,1)

        last=randint(1,2)+1

        print(Vibgyor[last-first], end= ‘:’)

(a)                 [‘G’, ‘Green’]: [‘G’, ‘Green’]: [‘Y’, ‘Yellow’]:

(b)                 [‘G’, ‘Green’]: [‘B’, ‘Blue’]: [‘G’, ‘Green’]:

(c)                 [‘V’, ‘Violet’]: [‘B’, ‘Blue’]: [‘B’, ‘Blue’]:

(d)                 [‘I’, ‘Indgo’]: [‘B’, ‘Blue’]: [‘B’, ‘Blue’]:


 

 

Q18. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum values that can be assigned to variable NUMBER.

import random

STRING=”CBSEONLINE”

NUMBER = random.randint (0, 3)

N=9

while STRING[N] != “L”:

    print (STRING[N] + STRING[NUMBER] +  “#”, end = ” “)

    NUMBER = NUMBER +1

    N=N-1

(a) ES#NE#IO#                     (b)LE#NO#ON#                   (c)NS#IE#LO#                      (d)EC#NB#IS#

 

 

 

Q19. What are the possible outcome(s) executed from the following code?

import random
print (int( 20 + random.random()*5), end =” “)
print (int( 20+ random.random()*5), end =” “)
print (int(20 + random.random()*5), end = ” “)
print (int( 20 + random.random()*5))
Find the suggested output options (i) to (iv). Also, write the least value and highest value that can be generated.

(i) 20 22 24 25                (ii) 22 23 24 25                  (iii) 23 24 23 24                   (iv) 21 21 21 21

 

 

 

Q20. What are the possible outcome(s) executed from the following code?

import random
print (100 + random.randint(5, 10), end = ‘ ‘)
print (100 + random.randint(5, 10), end = ‘ ‘)
print (100 + random.randint(5, 10), end = ‘ ‘)
print (100 + random.randint(5, 10))
Find the suggested output options (i) to (iv).

Also, write the least value and highest value that can be generated.

(i) 102 105 104 105      (ii) 110 103 104 105       (iii) 105 107 105 110     (iv) 110 105 105 110

 

Q21. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum values that can be assigned to variable NUMBER.

import random

PICK = random.randint (0, 3)

CITY = [“DELHI”, “MUMBAI”, “CHENNAI”, “KOLKATA”]

for I in CITY :

    for j in range(1, PICK):

        print(I, end =” “)

    print()

(i) DELHIDELHI
MUMBAIMUMBAI
CHENNAICHENNAI
KOLKATAKOLKATA

(ii) DELHI
DELHIMUMBAI
DELHIMUMBAICHENNAI

(iii) DELHI
MUMBAI
CHENNAI
KOLKATA

(iv) DELHI
MUMBAIMUMBAI
KOLKATAKOLKATAKOLKATA

 

 

 

Q22.  What possible output(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also, specify the maximum values that can be assigned to both the variables Y.

import random

X = random.randrange(1,4)

Y= random.random()

print(“%2d”, %(Y+X), “@”, X)

(a)           00 @ 0              (b) 01 @ 1                 (c) 02 @ 2                 (d) 04 @ 4

Ans: (b) & (c), Max value to Y:0,  Min value to Y: 1

 

 

 

Q23.  What possible output(s) are expected to be displayed on screen at the time of execution of the program from the following code?

import random

n=4

while n>1:

    val= random.randint(2,n)

    for m in range(val)

         if m%2= = 0:

                         print(m*2, end= “:”)

n=1

Output Option

(a)           0:4:0:0:             (b) 0:0:0:                   (c) 0:4:0:4:0                          (d) 0:4:0:4

Ans:

 

 

 

Q24. What possible output(s) is/are expected to be displayed on screen at the time of execution of the program from the following code? Also, specify the maximum values that can be assigned to the variables ‘Assigned’.

import random

Ar= [10,7]

Assigned = random.randrange(10)+1

for C in range(0,2,1):

      R=random.randint(1,2)-1

       print(Ar[R]+Assigned, “@”, end= “ ”)

(a)           11@8@                        (b) 20@21@             (c) 21@20@             (d) 8@11@

statistics module

This module provides functions for calculating mathematical statistics of numeric (Real-valued) data.

statistics.mean(data)

Return the sample arithmetic mean of data which can be a sequence or iterator.The arithmetic mean is the sum of the data divided by the number of data points(AVERAGE).
import statistics
print(statistics.mean([5,3,2]))
OUTPUT
3.3333333333333335

 

statistics.median(data)

Return the median (middle value) of numeric data, using the common “mean of  middle two” method. If data is empty, StatisticsError is raised.
import statistics
print(statistics.median([5,5,4,4,3,3,2,2]))
OUTPUT
3.5

 

statistics.mode(data)

Return the most common data point from discrete or nominal data. The mode (when it exists) is the most typical value, and is a robust measure of central location.If data is empty, or if there is not exactly one most common value,
StatisticsError is raised.
import statistics
print(statistics.mode([1, 1, 2, 3, 3, 3, 3, 4]))
OUTPUT
3

Click the button to see more MCQ

error: Content is protected !!