Class 12 Chapter 4 - 073304
Class 12 Chapter 4 - 073304
Python
Chapter: 4 “Using Python Libraries”
Er. Shivam Verma
Class 12th
Type A: Short Answer Questions/Conceptual Questions
Question 1
What is the significance of Modules?
Answer
The significance of Python modules is as follows:
Question 2
What are docstrings ? What is their significance? Give example to support your answer.
Answer
The docstrings are triple quoted strings in a Python module/program which are displayed as documentation when help
(<module-or-program-name>) command is displayed.
Significance of docstrings is as follows:
1. Documentation — Docstrings are used to document Python modules, classes, functions, and methods.
2. Readability — Well-written docstrings improve code readability by providing clear explanations of the code's
functionality.
3. Interactive Help — Docstrings are displayed as documentation when help (<module-or-program-name>) command is
displayed.
For example:
# tempConversion.py
"""Conversion functions between fahrenheit and centigrade"""
# Functions
def to_centigrade(x):
"""Returns: x converted to centigrade"""
return 5 * (x - 32) / 9.0
def to_fahrenheit(x):
"""Returns: x converted to fahrenheit"""
return 9 * x / 5.0 + 32
# Constants
FREEZING_C = 0.0 #water freezing temp.(in celcius)
FREEZING_F = 32.0 #water freezing temp.(in fahrenheit)
import tempConversion
help(tempConversion)
Output
Help on module tempConversion:
NAME
tempConversion-Conversion functions between fahrenheit and centigrade
FILE
c:\python37\pythonwork\tempconversion.py
FUNCTIONS
to_centigrade(x)
Returns : x converted to centigrade
to_fahrenheit(x)
2
Returns : x converted to fahrenheit
DATA
FREEZING_C = 0.0
FREEZING_F = 32.0
Question 3
What is a package? How is a package different from module?
Answer
A package is collection of Python modules under a common namespace, created by placing different modules on a single
directory along with some special files (such as __init__.py).
Difference between package and module:
Package Module
Question 4
What is a library? Write a procedure to create own library in Python.
Answer
A library refers to a collection of modules that together cater to specific t ype of requirements or applications.
The procedure to create own library in Python is shown below:
Question 5
What is the use of file __init__.py in a package even when it is empty?
Answer
The use of file __init__.py in a package even when it is empty is that without the __init__.py file, Python will not look for
submodules inside that directory, so attempts to import the module will fail. Hence, the file __init__.py in a folder, indica tes it
is an importable Python package.
Question 6
What is the importance of site-packages folder of Python installation?
Answer
The importance of site-packages folder of Python installation is that we can easily import a library and package using import
command in Python only if it is attached to site-packages folder as this is the default place from where python interpreter
imports Python library and packages.
3
Question 7
How are following import statements different?
(a) import X
(b) from X import *
(c) from X import a, b, c
Answer
(a) import X — This statement is used to import entire module X. All the functions are imported in a new namespace setup
with same name as that of the module X. To access one of the functions, we have to specify the name of the module (X) and
the name of the function, separated by a dot. This format is called dot notation.
(b) from X import * — This statement is used to import all the items from module X in the current namespace. We can use all
defined functions, variables etc from X module, without having to prefix module's name to imported item name.
(c) from X import a, b, c — This statement is used to import a, b, c objects from X module in the current namespace. We can
use a, b, c objects from X module, without having to prefix module's name to imported item name.
Question 8
What is Python PATH variable? What is its significance?
Answer
Python PATH variable is an environment variable used by python to specify directories where the python interpreter will look
in when importing modules.
The significance of the Python PATH variable lies in its ability to extend python's module search path. By adding directories to
the Python PATH variable, we can make python aware of additional locations where our custom modules or libraries are
located. Overall, the Python PATH variable provides flexibility and control over how python locates modules and packages,
allowing us to customize the module search path according to our needs.
Question 9
In which order Python looks for the function/module names used by you.
Answer
Python looks for the module names in the below order:
1. Built-in Modules — Python first looks for the module in the built-in modules that are part of the Python standard
library.
2. Directories in sys.path — If the module is not found in the built-in modules, Python searches for it in the directories
listed in the sys.path variable. The directories in sys.path typically include the current directory, directories specified
by the PYTHON PATH environment variable, and other standard locations such as the site-packages directory.
3. Current Directory — Python also looks for the module in the current directory where the Python script or interactive
session is running.
Question 10
What is the usage of help( ) and dir( ) functions.
Answer
help() function — This function is used to display docstrings of a module as documentation. The syntax is : help(<module-
name>)
dir() function — This function is used to display all the names defined inside the module. The syntax is : dir(<module-name>)
4
Question 11
Name the Python Library modules which need to be imported to invoke the following functions :
(i) log()
(ii) pow()
(iii) cos
(iv) randint
(v) sqrt()
Answer
The Python Library modules required to be imported for these functions are:
log() math
cos math
randint Random
sqrt() math
Question 12
What is dot notation of referring to objects inside a module?
Answer
After importing a module using import module statement, to access one of the functions, we have to specify the name of the
module and the name of the function, separated by a dot. This format is called dot notation.
For example:
import math
print(math.pi)
print(math.sqrt(25))
Question 13
Why should the from <module> import <object> statement be avoided to import objects ?
Answer
The from <module> import <object> statement should be avoided to import objects because it imports objects directly into
the current namespace. If a program already has a variable or function with the same name as the one imported via the module,
the imported object will overwrite the existing variable or function, leading to potential name clashes because there cannot be
two variables with the same name in one namespace.
Question 14
What do you understand by standard library of Python?
Answer
Python standard library is distributed with Python that contains modules for various types of functionalities. Some commonly
used modules of Python standard library are math module, random module, cmath module etc.
Question 15
Explain the difference between import <module> and from <module> import statements, with examples.
5
Answer
Question 1
Create module tempConversion.py as given in Fig. 4.2 in the chapter. If you invoke the module with two different types of
import statements, how would the function call statement for imported module's functions be affected?
Answer
If we invoke the tempConversion module with two different types of import statements (import tempConversion and from
tempConversion import *), the way we call the module's functions will be affected as follows:
1. import tempConversion — This imports the entire module in a new namespace setup with the same name as that of the
module tempConversion. To call the module's functions, we need to use the dot notation tempConversion.<function_name>.
For example:
6
import tempConversion
tempConversion.to_centigrade(32)
tempConversion.to_fahrenheit(0)
2. from tempConversion import * — This imports all objects (functions, variables, etc.) from the module into the current
namespace. This approach imports all objects directly into the current namespace, so we can call the module's functions
without using the module name.
For example:
from tempConversion import *
to_centigrade(32)
to_fahrenheit(0)
Question 2
A function checkMain() defined in module Allchecks.py is being used in two different programs. In program 1
as Allchecks.checkMain(3, 'A') and in program 2 as checkMain(4, 'Z'). Why are these two function-call statements different
from one another when the function being invoked is just the same?
Answer
Allchecks.checkMain(3, 'A') and checkMain(4, 'Z') these two function-call statements are different from one another when the
function being invoked is same because in Allchecks.checkMain(3, 'A') statement, Allchecks.py module is imported
using import Allchecks import statement in a new namespace created with the same name as that of module name and hence
they are called by dot notation whereas in checkMain(4, 'Z') statement Allchecks.py module is imported using from Allchecks
import checkMain import statement in the current namespace and hence its module name is not specified along with the
function name.
Question 3
Given below is semi-complete code of a module basic.py:
#
"""..............."""
def square(x):
"""..............."""
return mul(x, x)
...............mul(x, y):
"""..............."""
return x * y
def div(x, y):
"""..............."""
return float(x)/y
...............fdiv(x, y)...............
"""..............."""
...............x//y
def floordiv(x, y)...............
...............fdiv(x, y)
Complete the code. Save it as a module.
Answer
# basic.py
"""This module contains basic mathematical operations."""
def square(x):
"""Returns the square of a number."""
return mul(x, x)
7
def div(x, y):
"""Returns the result of dividing x by y."""
return float(x) / y
Question 4
After importing the above module, some of its functions are executed as per following statements. Find errors, if any:
(a) square(print 3)
(b) basic.div()
(c) basic.floordiv(7.0, 7)
(d) div(100, 0)
(e) basic.mul(3, 5)
(f) print(basic.square(3.5))
(g) z = basic.div(13, 3)
Answer
(a) square(print 3) — print function should not be there as parameter in the function call. So the correct function call statement
is square(3). Also, to call square function without prefixing the module name, it must be imported as from basic import square.
(b) basic.div() — The div() function requires two arguments but none are provided. So the correct statement is basic.div(x, y).
(d) div(100, 0) — This will result in a runtime error of ZeroDivisionError as we are trying to divide a number by zero. The
second argument of the function call should be any number other than 0. For example, div(100, 2). Also, to call div function
without prefixing the module name, it must be imported as from basic import div.
Question 5
Import the above module basic.py and write statements for the following:
(a) Compute square of 19.23.
(b) Compute floor division of 1000.01 with 100.23.
(c) Compute product of 3, 4 and 5. (Hint. use a function multiple times).
(d) What is the difference between basic.div(100, 0) and basic.div(0, 100)?
8
Answer
The statements are given in the program below:
import basic
# (d)
result2 = basic.div(0, 100)
result1 = basic.div(100, 0)
print("Result of basic.div(100, 0):", result1)
print("Result of basic.div(0, 100):", result2)
Output
Square of 19.23: 369.79290000000003
Floor division of 1000.01 by 100.23: 9.0
Product of 3, 4, and 5: 60
Result of basic.div(0, 100): 0.0
ZeroDivisionError
Explanation
(d) basic.div(100, 0) results in a ZeroDivisionError because division by zero is not defined whereas basic.div(0, 100) results in
0.0 as the quotient of '0 / 100'.
Question 6
Suppose that after we import the random module, we define the following function called diff in a Python session:
def diff():
x = random.random() - random.random()
return(x)
What would be the result if you now evaluate
y = diff()
print(y)
at the Python prompt ? Give reasons for your answer.
Answer
import random
def diff():
x = random.random() - random.random()
return(x)
y = diff()
print(y)
Output
0.006054151450219258
-0.2927493777465524
Explanation
9
Output will be a floating-point number representing the difference between two random numbers. Since every call to random()
function of random module generates a new number, hence the output will be different each time we run the code.
Question 7
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.
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
1. ES#NE#IO#
2. LE#NO#ON#
3. NS#IE#LO#
4. EC#NB#IS#
Answer
The outcomes are as follows:
ES#NE#IO#
EC#NB#IS#
NUMBER is assigned a random integer between 0 and 3 using random.randint(0, 3). Therefore, the minimum value for
NUMBER is 0 and the maximum value is 3.
Explanation
Length of STRING having value "CBSEONLINE" is 10. So the character at index 9 is "E". Since the value of N starts at 9 the
first letter of output will be "E". This rules out LE#NO#ON# and NS#IE#LO# as possible outcomes as they don't start with
"E". NUMBER is a random integer between 0 and 3. So, the second letter of output can be any letter from "CBSE". After
that, NUMBER is incremented by 1 and N is decremented by 1.
In next iteration, STRING[N] will be STRING[8] i.e., "N" and STRING[NUMBER] will be the letter coming immediately
after the second letter of the output in the string "CBSEONLINE" i.e., if second letter of output is "S" then it will be "E" and if
second letter is "C" then it will be "B".
In the third iteration, STRING[N] will be STRING[7] i.e., "I" and STRING[NUMBER] will be the letter coming immediately
after the fourth letter of the output in the string "CBSEONLINE" i.e., if fourth letter of output is "E" then it will be "O" and if
fourth letter is "B" then it will be "S".
After this the while loop ends as STRING[N] i.e., STRING[6] becomes "L". Thus both, ES#NE#IO# and EC#NB#IS# can be
the possible outcomes of this code.
Question 8
Consider 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 1 to 4. Also, write the least value and highest value that can be generated.
1. 20 22 24 25
2. 22 23 24 25
3. 23 24 23 24
4. 21 21 21 21
10
Answer
23 24 23 24
21 21 21 21
The lowest value that can be generated is 20 and the highest value that can be generated is 24.
Explanation
The lowest value that can be generated is 20 because random.random() can generate a value of 0, and (0 * 5) + 20 = 20. The
highest value that can be generated is 24 because the maximum value random.random() can return is just less than 1, and
(0.999... * 5) + 20 = 24.999..., which is truncated to 24 when converted to an integer.
Question 9
Consider 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 1 to 4. Also, write the least value and highest value that can be generated.
Answer
105 107 105 110
110 105 105 110
The least value that can be generated is 105 and the highest value that can be generated is 110.
Explanation
print(100 + random.randint(5, 10), end=' ') — This statement generates a random integer between 5 and 10, inclusive, and then
adds 100 to it. So, the suggested outputs range from 105 to 110.
The lowest value that can be generated is 100 + 5 = 105.
The highest value that can be generated is 100 + 10 = 110.
11
Question 10
Consider the following package
music/ Top-level package
├── __init__.py
├── formats/ Subpackage for file format
│ ├── __init__.py
│ └── wavread.py
│ └── wavwrite.py
│
├── effects/ Subpackage for sound effects
│ └── __init__.py
│ └── echo.py
│ └── surround.py
│ └── reverse.py
│
└── filters/ Subpackage for filters
├── __init__.py
└── equalizer.py
└── vocoder.py
└── karaoke.py
Each of the above modules contain functions play(), writefile() and readfile().
(a) If the module wavwrite is imported using command import music.formats.wavwrite. How will you invoke its writefile()
function ? Write command for it.
(b) If the module wavwrite is imported using command from music.formats import wavwrite. How will you invoke its
writefile() function ? Write command for it.
Answer
(a) If the module wavwrite is imported using the command import music.formats.wavwrite, we can invoke its writefile()
function by using the module name followed by the function name:
import music.formats.wavwrite
music.formats.wavwrite.writefile()
(b) If the module wavwrite is imported using the command from music.formats import wavwrite, we can directly invoke its
writefile() function without prefixing the module name:
from music.formats import wavwrite
writefile()
Question 11
What are the possible outcome(s) executed from the following code ? Also specify the maximum and minimum values that can
be assigned to variable PICK.
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()
1. DELHIDELHI
MUMBAIMUMBAI
CHENNAICHENNAI
KOLKATAKOLKATA
2. DELHI
DELHIMUMBAI
DELHIMUMBAICHENNAI
12
3. DELHI
MUMBAI
CHENNAI
KOLKATA
4. DELHI
MUMBAIMUMBAI
KOLKATAKOLKATAKOLKATA
Answer
DELHI
MUMBAI
CHENNAI
KOLKATA
DELHIDELHI
MUMBAIMUMBAI
CHENNAICHENNAI
KOLKATAKOLKATA
The minimum value for PICK is 0 and the maximum value for PICK is 3.
Explanation
13
Type C: Programming Practice/Knowledge based Questions
Question 1
Write a Python program having following functions:
Solution
def capwords_custom(sentence):
words = sentence.split()
capitalized_words = []
for word in words:
capitalized_word = word.capitalize()
capitalized_words.append(capitalized_word)
return ' '.join(capitalized_words)
Output
Enter a sentence: Hello there!
Enter a letter: e
After removing letter: Hllo thr!
Enter a sentence: python is best programming language
Custom capwords result: Python Is Best Programming Language
Capwords result from string module: Python Is Best Programming Language
Question 2
Create a module lengthconversion.py that stores functions for various lengths conversion e.g.,
It should also store constant values such as value of (mile in kilometers and vice versa).
14
[1 mile = 1.609344 kilometer ; 1 feet = 12 inches]
Help() function should display proper information.
Solution
# lengthconversion.py
"""Conversion functions for various lengths"""
#Constants
MILE_TO_KM = 1.609344
KM_TO_MILE = 1 / MILE_TO_KM
FEET_TO_INCHES = 12
INCHES_TO_FEET = 1 / FEET_TO_INCHES
#Functions
def miletokm(miles):
"""Returns: miles converted to kilometers"""
return miles * MILE_TO_KM
def kmtomile(kilometers):
"""Returns: kilometers converted to miles"""
return kilometers * KM_TO_MILE
def feettoinches(feet):
"""Returns: feet converted to inches"""
return feet * FEET_TO_INCHES
def inchestofeet(inches):
"""Returns: inches converted to feet"""
return inches * INCHES_TO_FEET
Output
5 miles to kilometers = 8.04672 km
5 kilometers to miles = 3.1068559611866697 miles
5 feet to inches = 60 inches
24 inches to feet = 2.0 feet
Question 3
Create a module MassConversion.py that stores function for mass conversion e.g.,
1.kgtotonne() — to convert kg to tonnes
2. tonnetokg() — to convert tonne to kg 3. kgtopound() — to convert kg to pound
4. poundtokg() — to convert pound to kg
(Also store constants 1 kg = 0.001 tonne, 1 kg = 2.20462 pound)
Help( ) function should give proper information about the module.
Solution
# MassConversion.py
"""Conversion functions between different masses"""
#Constants
KG_TO_TONNE = 0.001
TONNE_TO_KG = 1 / KG_TO_TONNE
KG_TO_POUND = 2.20462
POUND_TO_KG = 1 / KG_TO_POUND
#Functions
def kgtotonne(kg):
"""Returns: kilogram converted to tonnes"""
return kg * KG_TO_TONNE
def tonnetokg(tonne):
"""Returns: tonne converted to kilogram"""
return tonne * TONNE_TO_KG
def kgtopound(kg):
"""Returns: kilogram converted to pound"""
return kg * KG_TO_POUND
def poundtokg(pound):
"""Returns: pound converted to kilogram"""
15
return pound * POUND_TO_KG
Output
6 kilograms to tonnes = 0.006 tonnes
8 tonnes to kilograms = 8000.0 kilograms
5 kilograms to pound = 11.0231 pounds
18 pounds to kilograms = 8.164672369841515 kilograms
Question 4
Create a package from above two modules as this:
Conversion
├──Length
│ └──Lengthconversion.py
└──Mass
└──Massconversion. py
Make sure that above package meets the requirements of being a Python package. Also, you should be able to import above
package and/or its modules using import command.
Answer
1. The basic structure of above package includes packages's name i.e., Conversion and all modules and subfolders.
2. Create the directory structure having folders with names of package and subpackages. In the above package, we
created two folders by names Length and Mass. Inside these folders, we created Lengthconversion.py and
MassConversion.py modules respectively.
3. Create __init__.py files in package and subpackage folders. We created an empty file and saved it as "__init__.py"
and then copy this empty __init__.py file to the package and subpackage folders.
4. Associate it with python installation. Once we have our package directory ready, we can associate it with Python by
attaching it to Python's site-packages folder of current Python distribution in our computer.
5. After copying our package folder in site-packages folder of our current Python installation, now it has become a
Python library so that now we can import its modules and use its functions.
16