0% found this document useful (0 votes)
29 views26 pages

Python Libraries for Class 12 CBSE

This document provides an overview of Python libraries, including how to import modules, the significance of the __init__.py file in packages, and the differences between modules and packages. It includes multiple-choice questions, true/false questions, and short answer questions to reinforce understanding of concepts related to Python libraries. Key topics covered include importing methods, the structure of a library, and the role of docstrings for documentation.

Uploaded by

micex66246
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views26 pages

Python Libraries for Class 12 CBSE

This document provides an overview of Python libraries, including how to import modules, the significance of the __init__.py file in packages, and the differences between modules and packages. It includes multiple-choice questions, true/false questions, and short answer questions to reinforce understanding of concepts related to Python libraries. Key topics covered include importing methods, the structure of a library, and the role of docstrings for documentation.

Uploaded by

micex66246
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CBSE/ Class 12/ Python Libraries

Chapter 4

Using Python Libraries


Class 12 - Computer Science with Python Sumita Arora
Checkpoint 4.1

Question 1: Which operator is used in Python to import all modules from packages ?

1. . operator
2. * operator
3. -> symbol
4. , operator

Answer: * operator

Reason — The syntax to import all modules from package is : from <modulename> import *.
According to the syntax, * operator is used to import all modules from a package.

Question 2: Which file must be part of the folder containing Python module files to make it importable
Python package ?

1. [Link]
2. __setup__.py
3. __init__.py
4. [Link]

Answer: __init__.py

Reason — The file __init__.py in a folder, indicates it is an importable Python package, without
__init__.py, a folder is not considered a Python package.

Question 3: In Python which is the correct method to load a module math ?

1. include math
2. import math
3. #include<math.h>
4. using math

Answer

import math

Reason — The syntax for importing whole module is : import modulename. According to the syntax,
the correct method to load a module math is import math.

Question 4

Which is the correct command to load just the tempc method from a module called usable ?

Sumita Arora Solve pg. 1


CBSE/ Class 12/ Python Libraries
1. import usable, tempc
2. import tempc from usable
3. from usable import tempc
4. import tempc

Answer: from usable import tempc

Reason — The syntax for importing single method form a module is : from <module> import
<objectname>. According to the syntax, the correct method is from usable import tempc.

Question 5: What is the extension of Python library modules ?

1. .mod
2. .lib
3. .code
4. .py

Answer

.py

Reason — A Python library module has the .py extension.

Multiple Choice Questions

Question 1

A .py file containing constants/variables, classes, functions etc. related to a particular task and can be
used in other programs is called

1. module
2. library
3. classes
4. documentation

Answer

module

Reason — A Python module is a file (.py file) containing variables, class definitions, statements and
functions related to a particular task and can be used in other programs.

Question 2

The collection of modules and packages that together cater to a specific type of applications or
requirements, is called ...............

1. module
2. library
3. classes
4. documentation
Sumita Arora Solve pg. 2
CBSE/ Class 12/ Python Libraries
Answer: library

Reason — A library refers to a collection of modules and packages that together cater to a specific type
of applications or requirements.

Question 3: An independent triple quoted string given inside a module, containing documentation related
information is a ...............

1. Documentation string
2. docstring
3. dstring
4. stringdoc

Answer: docstring

Reason — The docstrings are triple quoted strings in a Python module/program which are displayed as
documentation when help (<module-or-program-name>) command is issued.

Question 4: The help <module> statement displays ............... from a module.

1. constants
2. functions
3. classes
4. docstrings

Answer : docstrings

Reason — Docstrings of a module are displayed as documentation, when help <module> statement is
issued.

Question 5: Which command(s) modifies the current namespace with the imported object name ?

1. import <module>
2. import <module1>, <module2>
3. from <module> import <object>
4. from <module> import *

Answer

from <module> import <object>


from <module> import *

Reason —

1. from <module> import <object>— This syntax is used to import a specific object from a
module into the current namespace.
2. from <module> import * — This syntax is used to import all objects from the module into the
current namespace.

Question 6: Which command(s) creates a separate namespace for each of the imported module ?

Sumita Arora Solve pg. 3


CBSE/ Class 12/ Python Libraries
1. import <module>
2. import <module1>, <module2>
3. from <module> import <object>
4. from <module> import *

Answer

import <module>
import <module1>, <module2>

Reason —

1. import <module> — This syntax is used to import an entire module. It creates a new namespace
with the same name as that of the module.
2. import <module1>, <module2> — This syntax is used to import multiple modules. It creates
separate namespaces for each module, with names corresponding to the module names.

Question 7: Which of the following random module functions generates a floating point number ?

1. random()
2. randint()
3. uniform()
4. all of these

Answer

random()
uniform()

Reason — Random module functions random() and uniform() both return random floating point
number .

Question 8: Which of the following random module functions generates an integer ?

1. random()
2. randint()
3. uniform()
4. all of these

Answer: randint()

Reason — Random module function randint() returns a random integer.

Question 9

Which file must be a part of a folder to be used as a Python package ?

1. [Link]
2. __init__.py
3. __package__.py
4. __module__.py

Sumita Arora Solve pg. 4


CBSE/ Class 12/ Python Libraries
Answer

__init__.py

Reason — For a folder containing Python files to be recognized as a package, an __init__.py file (even if
empty) must be part of the folder.

Question 10: A python module has ............... extension.

1. .mod
2. .imp
3. .py
4. .mpy

Answer

.py

Reason — A Python module has a .py extension.

Question 11: Which of the following is not a function/method of the random module in Python ?

1. randfloat()
2. randint()
3. random()
4. randrange()

Answer

randfloat()

Reason — Some most common random number generator functions in random module are random(),
randint(), uniform(), randrange(). Hence, randfloat() is not a function of random module.

Fill in the Blanks

Question 1

The file __init__.py must be the part of the folder holding library files and other definitions in order to be
treated as importable package.

Question 2

A library refers to a collection of modules that together cater to specific type of needs or applications.

Question 3

A Python module is a file (.py file) containing variables, class definitions, statements and functions
related to a particular task.

Question 4
Sumita Arora Solve pg. 5
CBSE/ Class 12/ Python Libraries
The uniform() function is the part of random module.

Question 5

The capwords() function is the part of string module.

True/False Questions

Question 1:A Python program and a Python module means the same.

Answer: False

Reason — A Python program is a set of instructions or code written in the Python programming language
that performs a specific task or a series of tasks. A Python module is a file containing Python code and is
saved with a .py extension. Hence, Python program and module are not same.

Question 2: A Python program and a Python module have the same .py file extension.

Answer: True

Reason — A Python program is saved in a .py file, which can be executed to perform a specific task. A
Python module is also a .py file containing Python code, but it's meant to be imported and used in other
Python programs or modules to reuse code. So, both Python programs and modules share the same file
extension, i.e., .py.

Question 3: The import <module> statement imports everything in the current namespace of the Python
program.

Answer: False

Reason — The import <module> statement imports entire module but it creates a new namespace with
the same name as that of the module.

Question 4: Any folder having .py files is a Python package.

Answer: False

Reason — Not all folders having multiple .py files are packages. In order for a folder containing Python
files to be recognized as a package, an __init__.py file must be part of the folder.

Question 5 : A folder having .py files along with a special file i.e, __init__.py in it is an importable
Python package.

Answer: True

Reason — The file __init__.py (even if empty) in a folder, indicates it is an importable Python package,
without __init__.py, a folder is not considered a Python package.

Question 6: The statement from <module> import <objects> is used to import a module in full.

Answer: False

Sumita Arora Solve pg. 6


CBSE/ Class 12/ Python Libraries
Reason — The statement from <module> import <objects> is used to import some selected items, not
all from a module.
Assertions and Reasons

Question 1

Assertion. The documentation for a Python module should be written in triple-quoted strings.

Reason. The docstrings are triple-quoted strings in Python that are displayed as documentation when help
<module> command is issued.

Answer

(a)

Both Assertion and Reason are true and Reason is the correct explanation of Assertion.

Explanation
Docstrings are typically written within triple-quoted strings (i.e., using """ or '''), which allows for
multiline strings. When the help<module> command is issued in Python, it retrieves and displays the
documentation string (docstring) associated with the specified modules, classes, functions, methods.

Question 2

Assertion. After importing a module through import statement, all its function definitions, variables,
constants etc. are made available in the program.

Reason. Imported module's definitions do not become part of the program's namespace if imported
through an import <module> statement.

Answer

(b)

Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.

Explanation
The import <module> statement imports the entire module, making its contents available in a new
namespace with the same name as the module. They do become accessible in the program's namespace
through dot notation, but they are not added directly to the current namespace.

Question 3

Assertion. If an item is imported through from <module> import <item> statement then you do not use
the module name along with the imported item.

Reason. The from <module> import command modifies the namespace of the program and adds the
imported item to it.

Answer

(a)

Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Sumita Arora Solve pg. 7
CBSE/ Class 12/ Python Libraries
Explanation
The from <module> import <item> command directly imports the specified item into the current
namespace. This means that the imported item becomes part of the program's namespace and can be
accessed directly without using the module name.

Question 4

Assertion. Python's built-in functions, which are part of the standard Python library, can directly be used
without specifying their module name.

Reason. Python's standard library's built-in functions are made available by default in the namespace of a
program.

Answer

(a)

Both Assertion and Reason are true and Reason is the correct explanation of Assertion.

Explanation
Python's built-in functions such as print(), len(), range() etc, are automatically added to the
program's namespace from the Python's standard library. They can be used directly without importing any
modules or specifying their module name.

Question 5

Assertion. Python offers two statements to import items into the current program : import and from
<module> import, which work identically.

Reason. Both import and from <module> import bring the imported items into the current program.

Answer

(e)

Both Assertion and Reason are false or not fully true.

Explanation
The import <module> statement imports the entire module into the new namespace setup with same
name as that of module, while the from <module> import <item> statement imports specific items
from the module into the current namespace. Hence, they both are different statements.

Type A: Short Answer Questions/Conceptual Questions

Question 1: What is the significance of Modules ?

Answer: The significance of Python modules is as follows:

1. Modules reduce complexity of programs to some degree.


2. Modules create a number of well-defined, documented boundaries within the program.
3. Contents of modules can be reused in other programs, without having to rewrite or recreate them.

Sumita Arora Solve pg. 8


CBSE/ Class 12/ Python Libraries
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:

# [Link]
"""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\[Link]
FUNCTIONS
to_centigrade(x)
Returns : x converted to centigrade
to_fahrenheit(x)
Returns : x converted to fahrenheit
DATA
FREEZING_C = 0.0
FREEZING_F = 32.0

Sumita Arora Solve pg. 9


CBSE/ Class 12/ Python Libraries
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

A package is a collection of Python modules A module is a single Python file containing


under a common namespace organized in variables, class definitions, statements and functions
directories. related to a particular task.

For a directory to be treated as a Python


package, __init__.py (which can be empty) __init__.py is not required for a Python module.
should be present.

Packages can contain sub-packages,


Modules cannot be nested.
forming a nested structure.

Question 4

What is a library ? Write procedure to create own library in Python.

Answer

A library refers to a collection of modules that together cater to specific type of requirements or
applications.
The procedure to create own library in Python is shown below:

1. Create a package folder having the name of the library.


2. Add module files (.py files containing actual code functions) to this package folder.
3. Add a special file __init__.py to it(even if the file is empty).
4. Attach this package folder to site-packages folder of Python installation.

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, indicates it is an importable Python package.

Question 6
Sumita Arora Solve pg. 10
CBSE/ Class 12/ Python Libraries
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.

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 :

Sumita Arora Solve pg. 11


CBSE/ Class 12/ Python Libraries
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 [Link] — If the module is not found in the built-in modules, Python searches for
it in the directories listed in the [Link] variable. The directories in [Link] 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>)

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:

Functions Python library module

log() math

pow() Built-in function

cos math

randint Random

sqrt() math

Sumita Arora Solve pg. 12


CBSE/ Class 12/ Python Libraries
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([Link])
print([Link](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.
Answer

import <module> statement from <module> import statement

It imports single, multiple or all objects from a


It imports entire module.
module.
To access one of the functions, we have to specify
the name of the module and the name of the To access functions, there is no need to prefix
function, separated by a dot. This format is called module's name to imported item name. The
dot notation. The syntax is : <module- syntax is : <function-name>
name>.<function-name>()

Imports all its items in a new namespace with the Imports specified items from the module into

Sumita Arora Solve pg. 13


CBSE/ Class 12/ Python Libraries
import <module> statement from <module> import statement

same name as of the module. the current namespace.


This approach can lead to namespace
This approach does not cause any problems. pollution and name clashes if multiple
modules import items with the same name.
For example: For example:
import math from math import pi, sqrt
print([Link]) print(pi)
print([Link](25)) print(sqrt(25))

Type B: Application Based Questions

Question 1

Create module [Link] 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:
import tempConversion
tempConversion.to_centigrade(32)
Sumita Arora Solve pg. 14
CBSE/ Class 12/ Python Libraries
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 [Link] is being used in two different programs. In
program 1 as [Link](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

[Link](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 [Link](3, 'A') statement, [Link] 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 [Link] 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 [Link] :

#
"""..............."""
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

# [Link]
"""This module contains basic mathematical operations."""

Sumita Arora Solve pg. 15


CBSE/ Class 12/ Python Libraries
def square(x):
"""Returns the square of a number."""
return mul(x, x)

def mul(x, y):


"""Returns the product of two numbers."""
return x * y

def div(x, y):


"""Returns the result of dividing x by y."""
return float(x) / y

def fdiv(x, y):


"""Returns the result of floor division of x by y."""
return x // y

def floordiv(x, y):


return fdiv(x, y)
The code is saved with .py extension to save it as module.

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) [Link]()

(c) [Link](7.0, 7)

(d) div(100, 0)

(e) [Link](3, 5)

(f) print([Link](3.5))

(g) z = [Link](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) [Link]() — The div() function requires two arguments but none are provided. So the correct
statement is [Link](x, y).
(c) [Link](7.0, 7) — There is no error.
(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.
(e) [Link](3, 5) — There is no error.

(f) print([Link](3.5)) — There is no error.


Sumita Arora Solve pg. 16
CBSE/ Class 12/ Python Libraries
(g) z = [Link](13, 3) — There is no error.

Question 5

Import the above module [Link] 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 [Link](100, 0) and [Link](0, 100)?

Answer

The statements are given in the program below:

import basic

# (a) Compute square of 19.23


square_result = [Link](19.23)
print("Square of 19.23:", square_result)

# (b) Compute floor division of 1000.01 with 100.23


floor_div_result = [Link](1000.01, 100.23)
print("Floor division of 1000.01 by 100.23:", floor_div_result)

# (c) Compute product of 3, 4 and 5


product_result = [Link]([Link](3, 4), 5)
print("Product of 3, 4, and 5:", product_result)

# (d)
result2 = [Link](0, 100)
result1 = [Link](100, 0)
print("Result of [Link](100, 0):", result1)
print("Result of [Link](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 [Link](0, 100): 0.0
ZeroDivisionError

Explanation

(d) [Link](100, 0) results in a ZeroDivisionError because division by zero is not defined


whereas [Link](0, 100) results in 0.0 as the quotient of '0 / 100'.

Question 6

Sumita Arora Solve pg. 17


CBSE/ Class 12/ Python Libraries
Suppose that after we import the random module, we define the following function called diff in a
Python session :
def diff():
x = [Link]() - [Link]()
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 = [Link]() - [Link]()
return(x)

y = diff()
print(y)

Output

0.006054151450219258
-0.2927493777465524

Explanation

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 = [Link](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

Sumita Arora Solve pg. 18


CBSE/ Class 12/ Python Libraries
The outcomes are as follows:

ES#NE#IO#
EC#NB#IS#

NUMBER is assigned a random integer between 0 and 3 using [Link](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 + [Link]() * 5), end = ' ')
print(int(20 + [Link]() * 5), end = ' ')
print(int(20 + [Link]() * 5), end = ' ')
print(int(20 + [Link]() * 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

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

1. import random — This line imports the random module.

Sumita Arora Solve pg. 19


CBSE/ Class 12/ Python Libraries
2. print(int(20 + [Link]() * 5), end=' ') — This line generates a random float
number using [Link](), which returns a random float in the range (0.0, 1.0) exclusive of
1. The random number is then multiplied with 5 and added to 20. The int() function converts the
result to an integer by truncating its decimal part. Thus, int(20 + [Link]() * 5) will
generate an integer in the range [20, 21, 22, 23, 24]. The end=' ' argument in the print() function
ensures that the output is separated by a space instead of a newline.
3. The next print statements are similar to the second line, generating and printing two more random
integers within the same range.

The lowest value that can be generated is 20 because [Link]() can generate a value of 0, and (0 *
5) + 20 = 20. The highest value that can be generated is 24 because the maximum value [Link]()
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 + [Link](5, 10), end = ' ' )
print(100 + [Link](5, 10), end = ' ' )
print(100 + [Link](5, 10), end = ' ' )
print(100 + [Link](5, 10))
Find the suggested output options 1 to 4. Also, write the least value and highest value that can be
generated.

1. 102 105 104 105


2. 110 103 104 105
3. 105 107 105 110
4. 110 105 105 110

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 + [Link](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.

Question 10

Consider the following package

music/ Top-level package


├── __init__.py
├── formats/ Subpackage for file format
Sumita Arora Solve pg. 20
CBSE/ Class 12/ Python Libraries
│ ├── __init__.py
│ └── [Link]
│ └── [Link]

├── effects/ Subpackage for sound effects
│ └── __init__.py
│ └── [Link]
│ └── [Link]
│ └── [Link]

└── filters/ Subpackage for filters
├── __init__.py
└── [Link]
└── [Link]
└── [Link]
Each of the above modules contain functions play(), writefile() and readfile().

(a) If the module wavwrite is imported using command import [Link]. How will you
invoke its writefile() function ? Write command for it.

(b) If the module wavwrite is imported using command from [Link] 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 [Link], we can
invoke its writefile() function by using the module name followed by the function name:
import [Link]
[Link]()
(b) If the module wavwrite is imported using the command from [Link] import wavwrite,
we can directly invoke its writefile() function without prefixing the module name:
from [Link] 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 = [Link](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

Sumita Arora Solve pg. 21


CBSE/ Class 12/ Python Libraries
2. DELHI
DELHIMUMBAI
DELHIMUMBAICHENNAI
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

1. import random — Imports the random module.


2. PICK = [Link](0, 3) — Generates a random integer between 0 and 3 (inclusive) and
assigns it to the variable PICK.
3. CITY = ["DELHI", "MUMBAI", "CHENNAI", "KOLKATA"] — Defines a list of cities.
4. for I in CITY — This loop iterates over each city in the CITY.
5. for J in range(1, PICK) — This loop will iterate from 1 up to PICK - 1. The value
of PICK can be an integer in the range [0, 1, 2, 3]. For the cases when value of PICK is 0 or 1, the
loop will not execute as range(1, 0) and range(1, 1) will return empty range.
For the cases when value of PICK is 2 or 3, the names of the cities in CITY will be printed once or
twice, respectively. Hence, we get the possible outcomes of this code.

Type C: Programming Practice/Knowledge based Questions

Question 1

Write a Python program having following functions :

1. A function with the following signature : remove_letter(sentence, letter)


This function should take a string and a letter (as a single-character string) as arguments, returning
a copy of that string with every instance of the indicated letter removed. For example,
remove_letter("Hello there!", "e") should return the string "Hllo thr!".
Try implementing it using <str>.split() function.
2. Write a function to do the following :
Try implementing the capwords() functionality using other functions, i.e., split(), capitalize() and
join(). Compare the result with the capwords() function's result.
Sumita Arora Solve pg. 22
CBSE/ Class 12/ Python Libraries
Solution

def remove_letter(sentence, letter):


words = [Link]()
new_sentence = []
for word in words:
new_word = ''
for char in word:
if [Link]() != [Link]():
new_word += char
new_sentence.append(new_word)
return ' '.join(new_sentence)

def capwords_custom(sentence):
words = [Link]()
capitalized_words = []
for word in words:
capitalized_word = [Link]()
capitalized_words.append(capitalized_word)
return ' '.join(capitalized_words)

sentence = input("Enter a sentence: ")


letter = input("Enter a letter: ")
print("After removing letter:", remove_letter(sentence, letter))

from string import capwords


sentences_input = input("Enter a sentence: ")
sentences = sentences_input.split('.')

for sentence in sentences:


sentence = [Link]()
print("Custom capwords result:", capwords_custom(sentence))
print("Capwords result from string module:", capwords(sentence))

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 [Link] that stores functions for various lengths conversion e.g.,

1. miletokm() — to convert miles to kilometer


2. kmtomile() — to convert kilometers to miles
3. feettoinches()
4. inchestofeet()
Sumita Arora Solve pg. 23
CBSE/ Class 12/ Python Libraries
It should also store constant values such as value of (mile in kilometers and vice versa).

[1 mile = 1.609344 kilometer ; 1 feet = 12 inches]

Help() function should display proper information.

Solution

# [Link]
"""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 [Link] that stores function for mass conversion e.g.,
[Link]() — 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

Sumita Arora Solve pg. 24


CBSE/ Class 12/ Python Libraries
# [Link]
"""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"""
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
│ └──[Link]
└──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 [Link] and [Link] modules respectively.

Sumita Arora Solve pg. 25


CBSE/ Class 12/ Python Libraries
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.

Directory structure is as follows:

Conversion/
├── __init__.py
├── Length/
│ ├── __init__.py
│ └── [Link]
└── Mass/
├── __init__.py
└── [Link]

Sumita Arora Solve pg. 26

Common questions

Powered by AI

Using random.randint(), which generates random integers within a specified range, the outputs of the while loop in the code example provided can vary. For instance, the code generates outcomes such as 'ES#NE#IO#' and 'EC#NB#IS#' depending on the initial value assigned to the variable NUMBER, which ranges between 0 and 3. In both cases, the loop continues until a character sequence with 'L' is encountered, increasing NUMBER by 1 in each iteration .

Using 'from <module> import *' in a large Python project can lead to several consequences: it pollutes the namespace with all module contents, potentially causing naming conflicts and unexpected behavior if different modules have functions or variables with the same name. This import method makes it harder to debug and understand code, as it's unclear which module a certain function or variable comes from without explicit prefixes .

The __init__.py file plays a critical role in Python packaging as it indicates to Python that the directory is a package. Even if the file is empty, its presence marks the directory as a Python package and allows the Python interpreter to consider any submodules within the directory for import. Without __init__.py, Python will not recognize the directory as a package, and import attempts will fail .

Differences in function call statements, such as using Allchecks.checkMain() versus checkMain(), significantly affect program structure and readability. Importing with 'import <module>' requires specifying the module name when calling its functions, making the code explicit but verbose. Using 'from <module> import <function>' allows direct function calls, enhancing readability but sacrifices clarity regarding the function's origin, potentially causing confusion in complex projects .

The site-packages folder is significant because it is the default directory where Python looks for third-party modules and packages to import. When a package is installed, it's typically placed in the site-packages directory, allowing the Python interpreter to easily find and import it without needing additional configuration. This directory's organization is crucial for seamless package management and functionality .

The primary purpose of a docstring in a Python module is to serve as documentation for the module. Docstrings are written as triple-quoted strings at the beginning of a module, function, class, or method in Python. They are accessed using the help command in Python, which displays the docstring content as the documentation of the module .

The statement basic.div(100, 0) would result in a ZeroDivisionError because dividing by zero is undefined in mathematics and in Python programming, leading to a runtime error. Conversely, basic.div(0, 100) would not cause a runtime error; it would simply return 0.0, representing zero divided by a non-zero number .

A 'Python program' is a standalone script intended to perform a specific task or set of tasks directly when executed, often containing a main method to run code. In contrast, a 'Python module' is a .py file designed to be imported by other scripts and reuse its classes, methods, or variables. The .py extension is a common file type for both, but their use cases and design purposes differ significantly .

When you use "import <module>", it imports the entire module and creates a new namespace for it. This means you have to prefix the module name to access its functions or classes. "from <module> import <object>" imports specific objects from a module into the current namespace, allowing you to access them without a prefix. "from <module> import *" imports all objects from a module into the current namespace, which can lead to naming conflicts if there are overlapping names .

The selection of integers generated by the expression int(20 + random.random() * 5) is influenced by the random.random() function, which generates a floating-point number between 0.0 (inclusive) and 1.0 (exclusive). By multiplying this random float by 5 and adding 20, we create a range of floats from 20.0 to less than 25.0. The int() function truncates the decimal, producing an integer within the range of 20 to 24, inclusive .

You might also like