| STUDY MATERIAL LOGIN JOIN NOW
Home / Class 12 - Computer Science with Python Sumita Arora / Using Python Libraries
CONTENTS
Search by lesson title
Chapter 4
Using Python Libraries
Checkpoint 4.1
Chapter 1
Multiple Choice Questions
Python Revision Tour
Class 12 - Computer Science with Python Sumita Arora Fill in the Blanks
Chapter 2
True/False Questions
Python Revision Tour II
Assertions and Reasons
Chapter 3 Type A: Short Answer
Working with Functions
Checkpoint 4.1 Questions/Conceptual
Questions
Chapter 4
Type B: Application Based
Using Python Libraries
Questions
Chapter 5
File Handling
Question 1 Type C: Programming
Practice/Knowledge based
Questions
Chapter 8
Data Structures - I : Linear Lists
Which operator is used in Python to import
Chapter 10
Computer Networks - I all modules from packages ?
Chapter 11
Computer Networks - II
Chapter 12
1. . operator
Relational Databases
Chapter 13
2. * operator
Simple Queries in SQL
Chapter 14 3. -> symbol
Table Creation and Data Manipulation
Commands
Chapter 15
4. , operator
Grouping Records, Joins in SQL
Chapter 16
Interface Python with MySQL
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 ?
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
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
?
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
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
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
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.
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.
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 fahrenhei
# 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.(i
FREEZING_F = 32.0 #water freezing temp.(
import tempConversion
help(tempConversion)
Output
Help on module tempConversion:
NAME
tempConversion-Conversion functions b
FILE
c:\python37\pythonwork\tempconversion
FUNCTIONS
to_centigrade(x)
Returns : x converted to centigra
to_fahrenheit(x)
Returns : x converted to fahrenhe
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
A package is a A module is a
collection of single Python file
Python modules containing
Package Module
under a common variables, class
namespace definitions,
organized in statements and
directories. functions related to
a particular task.
For a directory to
be treated as a
__init__.py is not
Python package,
required for a
__init__.py (which
Python module.
can be empty)
should be present.
Packages can
contain sub-
Modules cannot be
packages, forming
nested.
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
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 :
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
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
from <module>
import <module>
import
statement
statement
It imports
It imports entire single, multiple
module. or all objects
from a module.
from <module>
import <module>
import
statement
statement
To access one of the
To access
functions, we have to
functions, there
specify the name of
is no need to
the module and the
prefix module's
name of the function,
name to
separated by a dot.
imported item
This format is called
name. The
dot notation. The
syntax is :
syntax is : <module-
<function-
name>.<function-name>
name>
()
Imports
Imports all its items in specified items
a new namespace from the
with the same name module into the
as of the module. current
namespace.
This approach
can lead to
namespace
This approach does pollution and
not cause any name clashes
problems. if multiple
modules import
items with the
same name.
from <module>
import <module>
import
statement
statement
For example:
For example:
from math
import 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)
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 mathematica
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 b
return float(x) / y
def fdiv(x, y):
"""Returns the result of floor divisi
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.
(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 w
floor_div_result = [Link](1000.01
print("Floor division of 1000.01 by 100.2
# (c) Compute product of 3, 4 and 5
product_result = [Link]([Link](3,
print("Product of 3, 4, and 5:", product_
# (d)
result2 = [Link](0, 100)
result1 = [Link](100, 0)
print("Result of [Link](100, 0):", res
print("Result of [Link](0, 100):", res
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
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] + '#
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 [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.
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 p
├── __init__.py
├── formats/ Subpackage
│ ├── __init__.py
│ └── [Link]
│ └── [Link]
│
├── effects/ Subpackage
│ └── __init__.py
│ └── [Link]
│ └── [Link]
│ └── [Link]
│
└── filters/ Subpackage
├── __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", "KO
for I in CITY :
for J in range(1, PICK):
print(I, end = " ")
print()
1. DELHIDELHI
MUMBAIMUMBAI
CHENNAICHENNAI
KOLKATAKOLKATA
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.
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(capitaliz
return ' '.join(capitalized_words)
sentence = input("Enter a sentence: ")
letter = input("Enter a letter: ")
print("After removing letter:", remove_le
from string import capwords
sentences_input = input("Enter a sentence
sentences = sentences_input.split('.')
for sentence in sentences:
sentence = [Link]()
print("Custom capwords result:", capw
print("Capwords result from string mo
Output
Enter a sentence: Hello there!
Enter a letter: e
After removing letter: Hllo thr!
Enter a sentence: python is best programm
Custom capwords result: Python Is Best Pr
Capwords result from string module: Pytho
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()
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 lengt
#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 kilome
return miles * MILE_TO_KM
def kmtomile(kilometers):
"""Returns: kilometers converted to m
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.106855961186669
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
# [Link]
"""Conversion functions between different
#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 ton
return kg * KG_TO_TONNE
def tonnetokg(tonne):
"""Returns: tonne converted to kilogr
return tonne * TONNE_TO_KG
def kgtopound(kg):
"""Returns: kilogram converted to pou
return kg * KG_TO_POUND
def poundtokg(pound):
"""Returns: pound converted to kilogr
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.16467236984151
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.
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]
Prev Next
Working with Functions File Handling
ICSE/ISC TEXTBOOK SOLUTIONS ICSE/ISC/CBSE PRACTICE TESTS COMPANY
Class - 6 Concise Physics Selina Solutions Class - 9 ICSE Mathematics Practice Tests Pricing
Class - 6 Viva Physics Solutions Class - 9 ICSE Mathematics Sample Paper Tests About Us
Class - 6 Concise Chemistry Selina Solutions Class - 9 ICSE Physics Practice Tests Contact Us
Class - 6 Concise Biology Selina Solutions Class - 9 ICSE Physics Sample Paper Tests Privacy Policy
Class - 6 Frank Geography Solutions Class - 9 ICSE Biology Practice Tests Terms of Service
Class - 6 Veena Bhargava Geography Solutions Class - 9 ICSE Computer Applications Practice Tests
Class - 6 Frank History & Civics Solutions Class - 10 ICSE Mathematics Practice Tests
Class - 6 Effective History & Civics Solutions Class - 10 ICSE Mathematics Sample Paper Tests
Class - 7 Concise Physics Selina Solutions Class - 10 ICSE Physics Practice Tests
Class - 7 Concise Chemistry Selina Solutions Class - 10 ICSE Physics Sample Paper Tests
Class - 7 Dalal Simplified Middle School Chemistry Solutions Class - 10 ICSE Biology Practice Tests
Class - 7 Concise Biology Selina Solutions Class - 10 ICSE Biology Sample Paper Tests
Class - 7 Living Science Biology Ratna Sagar Solutions Class - 10 ICSE Computer Applications Practice Tests
Class - 7 Around the World Geography Solutions Class - 10 ICSE Computer Applications Sample Paper Tests
Class - 7 Veena Bhargava Geography Solutions Class - 12 CBSE Computer Science Practice Tests
Class - 7 Effective History & Civics Solutions Class - 12 CBSE Computer Science Sample Paper Tests
Class - 8 Concise Physics Selina Solutions Class - 12 CBSE Informatics Practices Sample Paper Tests
STUDYLIST
Class - 8 Concise Chemistry Selina Solutions
Java Pattern Programs
Class - 8 Dalal Simplified Middle School Chemistry Solutions
Java Series Programs
Class - 8 Concise Biology Selina Solutions
Java Number Programs (ICSE Classes 9 / 10)
Class - 8 Living Science Biology Ratna Sagar Solutions
Java Number Programs (ISC Classes 11 / 12)
Class - 8 Around the World Geography Solutions
Output Questions for Class 10 ICSE Computer Applications
Class - 8 Veena Bhargava Geography Solutions
Algorithms & Flowcharts for ICSE Computers
Class - 8 Effective History & Civics Solutions
ICSE Class 8 Computers Differentiate Between the Following
Class - 8 Kips Logix Computers Solutions
CBSE Class 12 Computer Science Important Output Questions
Class - 9 Concise Physics Selina Solutions
CBSE Class 12 Computer Science Assertion Reason Questions
Class - 9 Concise Chemistry Selina Solutions
CBSE Class 12 Computer Science File Handling Questions
Class - 9 Dalal Simplified ICSE Chemistry Solutions
CBSE TEXTBOOK SOLUTIONS
Class - 9 Concise Biology Selina Solutions
Class - 8 NCERT Science Solutions
Class - 9 Total Geography Morning Star Solutions
Class - 9 NCERT Mathematics Solutions
Class - 9 Veena Bhargava Geography Solutions
Class - 9 NCERT Science Solutions
Class - 9 Total History & Civics Solutions
Class - 9 NCERT Geography Contemporary India 1 Solutions
Class - 9 DN Kundra History & Civics Solutions
Class - 9 NCERT History India & Contemporary World 1 Solutions
Class - 9 Kips Logix Computers Solutions
Class - 9 Sumita Arora Computer Code 165 Solutions
Class - 10 Concise Physics Selina Solutions
Class - 9 Kips Cyber Beans Computer Code 165 Solutions
Class - 10 Concise Chemistry Selina Solutions
Class - 10 NCERT Mathematics Solutions
Class - 10 Dalal Simplified ICSE Chemistry Solutions
Class - 10 NCERT Science Solutions
Class - 10 Concise Biology Selina Solutions
Class - 10 NCERT Geography Contemporary India 2 Solutions
Class - 10 Total Geography Morning Star Solutions
Class - 10 NCERT History India & Contemporary World 2 Solutions
Class - 10 Veena Bhargava Geography Solutions
Class - 10 NCERT Democratic Politics 2 (Civics) Solutions
Class - 10 Total History & Civics Solutions
Class - 10 NCERT Economic Development Solutions
Class - 10 DN Kundra History & Civics Solutions
Class - 10 Sumita Arora Computer Code 165 Solutions
Class - 10 Sumita Arora ICSE Computers Solutions
Class - 10 Kips Cyber Beans Computer Code 165 Solutions
Class - 10 Kips Logix Computers Solutions
Class - 11 CBSE Sumita Arora Python Solutions
Selina ICSE Concise Solutions
Class - 11 CBSE Preeti Arora Python Solutions
Morning Star ICSE Solutions
Class - 11 CBSE Informatics Practices Preeti Arora Solutions
ICSE Board Solved Question Papers
Class - 12 CBSE Sumita Arora Python Solutions
ICSE Competency Based Questions
ICSE/ISC SOLVED QUESTION PAPERS Class - 12 CBSE Preeti Arora Python Solutions
Class - 10 ICSE Maths Solved Competency Focused Questions Class - 12 NCERT Computer Science Solutions
Class - 10 ICSE Physics Solved Competency Focused Questions Class - 12 CBSE Informatics Practices Sumita Arora Solutions
Class - 10 ICSE Chemistry Solved Competency Focused Questions Class - 12 CBSE Informatics Practices Preeti Arora Solutions
Class - 10 ICSE Biology Solved Competency Focused Questions CBSE Board Solved Question Papers
Class - 10 ICSE Geography Solved Competency Focused Questions
Class - 10 ICSE History & Civics Solved Competency Focused
Questions
Class - 10 ICSE Computer Applications Solved Competency
Focused Questions
ICSE Class 10 Computers Solved 10 Yrs Question Papers
ICSE Class 10 Physics Solved 10 Yrs Question Papers
ICSE Class 10 Chemistry Solved 10 Yrs Question Papers
ICSE Class 10 Biology Solved 10 Yrs Question Papers
ICSE Class 10 Maths Solved Previous Yrs Question Papers
ICSE Class 10 History Solved Previous Yrs Question Papers
Class - 12 ISC Computer Science Solved Practical Papers
Class - 10 CBSE Computer Applications Solved Question Papers
Class - 10 CBSE Science Solved Question Papers
Class - 12 CBSE Computer Science Solved Question Papers
Class - 12 CBSE Informatics Practices Solved Question Papers
Copyright © KnowledgeBoat 2025