xii cs chapter4 solutions
xii cs chapter4 solutions
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. init.py
2. __setup__.py
3. __init__.py
4. setup.py
Answer
__init__.py
Question 3
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 ?
Answer
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
1. .mod
2. .lib
3. .code
4. .py
Answer
.py
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
1. constants
2. functions
3. classes
4. docstrings
Answer
docstrings
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
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
1. random()
2. randint()
3. uniform()
4. all of these
Answer
randint()
Question 9
1. package.py
2. __init__.py
3. __package__.py
4. __module__.py
Answer
__init__.py
1. .mod
2. .imp
3. .py
4. .mpy
Answer
.py
Question 11
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.
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
Question 5
True/False Questions
Question 1
Answer
False
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
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)
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
Answer
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.
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
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)
Returns : x converted to fahrenheit
DATA
FREEZING_C = 0.0
FREEZING_F = 32.0
Question 3
Answer
Package Module
A package is a collection of Python modules A module is a single Python file containing variables,
under a common namespace organized in class definitions, statements and functions related to a
directories. particular task.
Question 4
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:
Question 5
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
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
(a) import X
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
Answer
Question 9
In which order Python looks for the function/module names used by you.
Answer
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
Answer
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
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
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
Imports all its items in a new namespace with the same name as Imports specified items from the module
of the module. into the current namespace.
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:
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
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
#
"""..............."""
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)
Answer
# basic.py
"""This module contains basic mathematical operations."""
def square(x):
"""Returns the square of a number."""
return mul(x, x)
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).
(c) basic.floordiv(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) basic.mul(3, 5) — There is no error.
Question 5
Import the above module basic.py and write statements for the following :
Answer
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
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)
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
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
ES#NE#IO#
EC#NB#IS#
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
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
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
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
The least value that can be generated is 105 and the highest value that can be generated is
110.
Explanation
Question 10
(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
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
Question 1
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
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).
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
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
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"""
return pound * POUND_TO_KG
Output
Question 4
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.
Conversion/
├── __init__.py
├── Length/
│ ├── __init__.py
│ └── Lengthconversion.py
└── Mass/
├── __init__.py
└── MassConversion.py