0% found this document useful (0 votes)
11 views12 pages

1

The document discusses Python libraries, modules, and packages, explaining how to import them and the differences between them. It includes multiple-choice and true/false questions to test knowledge on these topics, along with explanations of built-in functions and the significance of docstrings. Additionally, it provides examples of code and expected outputs to illustrate the concepts discussed.

Uploaded by

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

1

The document discusses Python libraries, modules, and packages, explaining how to import them and the differences between them. It includes multiple-choice and true/false questions to test knowledge on these topics, along with explanations of built-in functions and the significance of docstrings. Additionally, it provides examples of code and expected outputs to illustrate the concepts discussed.

Uploaded by

enggpranjal9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
- cjopor 42 USING PYTHON UBRARIES There are ewo forms of import statements Gi import [as ] (ii) from Import statement displays from a module. (a) constants (®) functions (©) classes Hay docstrings 5. Which command(s) modifies the current namespace with the imported object name ? (a) import (® import , Ae) from import éy rom import * 6. Which command(s) creates a separate namespace for each of the imported module ? av import Lr import , from import import * 7. Mihich of the following random module functions generates a floating point number ? Jay random( ) @ randint() ley tuniform( ) (@) all of these 8. Which of the following random module functions generates an integer ? (a) random( ) (Wyrandint( ) (0) uniform( ) (d) all of these 9. Which file must be a part of a folder to be used as a Python package ? (a) package.py Dy cinit_py (c) __package_.py (d) ___module_.py_ 10. A Python module has _____ extension. (@) «mod () imp rey (@) mpy 11. Which of the following is not a function/method of the random module in Python ? {CBSE Paper 2021 (Term 1] Ley Fandfloat( ) (®) randint( ) (©) random( ) (@) randrange( ) > COMPUTER SCIENCE wi a ITH PYTHON _ FILLIN THE BLANKS: ey paneer 1. The file must be the part of the fold be treated as importable package. AW bY refers toa collection of modules that together cater to specific type of needs on Aa the hol g library S and other definitions in order, applications...) 8. A Python "isa file (py file) containing, variables, class definitions, statements and function related to a particular task. Kander : 4. The uniform() function is the part of module, nis the part of 4°") module, TRUE/FALSE QUESTIONS A Python program and a Python module means the same. 5. ‘The capwords() funeti A Python program and a Python module have the same py file extension’ 2 ‘The import statement imports everything in the current namespace of the Python program, . Any folder having .py files is a Python package.F A folder havi PY files along with a special file ‘e,,_init_.py in itis an importable Python packagd 6. The statement from import is used to import a module in full. FF ASSERTIONS AND REASONS DIRECTIONS In the following questions, a statement of Assertion (A) is followed by a statement of Reason (R). ‘Mark the correct choice as : (a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (© Ais true but R is false (or partly true). (@ A is false (or partly true) but R is true. (©) Both A and R are false or not fully true. 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 command is issued, 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 statement. 3. Assertion. If an item is imported through from import use the module name along with the imported item. ‘Reason. The from import command modifies the namespace of the program and adds the imported item to it, m> statement then you do net 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 dard library's built namespace of a program. in functions are made available by default in the “i ea sn PYTHON UDRARIES corte : " cestion (A): Python standard tibrary consists of (R). A function ina module number of modules, Reasoning is used to simpli > ed to simplify the code and avoids repetition ython offers two A = cecrtion. Python of Statements to import 6 MMyemoduie>import, which work identically OG C eason. Both import and from Smodule> import bring the imported items into the current program. sorts Answers for OTOs are given at the end of the book ved Problems what is a module, package and a library ? SolutionModule. A module is a file with some Python code and is saved with a .py extension. Package. A package is a directory that contains subpackages and modules in it along with some special files such as __init_py. Library. A Python library is a reusable chunk of code that is used in program/script using import command. A package is a library if itis installable or gets attached to site-packages folder of Python installation. The line between a package and a Python library is quite blurred and both these terms are often used interchangeably. What is a Python module ? What is its significance ? Solution. A “module” is a chunk of Python code that exists in its own (.py ) file and is intended to be used by Python code outside itself. ‘Modules allow one to bundle together code in a form in which it can easily be used later. The Modules can be “imported” in other programs so the functions and other definitions in imported modules become available to code that imports them. 3. What is the utility of built-in function help( ) ? Solution. Python’s built-in function help( ) is very useful. When it is provided with a program-name or a modtile-name or a function-name as an argument, it displays the documentation of the argument as help. It also displays the docstrings within its passed-argument’s definition. For example, help(math) will display the documentation related to module math. It can even take function name as argument, ¢g help(math. sqrt) The above code will list the documentation of math.sqrt() function only. What are docstrings ? How are they useful ? oe Solution. A docstring is just a regular Python triple-quoted string that is the first thing in a function body /a module / a class. When executing a function body (or a module / class), the docstring doesn’t do anything like other comments, but Python stores it as part of the function documentation. This documentation can later be displayed using help( ) function. So, even though docstrings appear like comments (no execution) but these are different from comments. 180 COMPUTER SCIENCE WITH PrTHN, ~ 5. What happens rolen Python encounters an import statement in a program: ? What would happen, one more import statement for the same module, already imported in the same program ? Solution, When Python encounters an import statement, it does the following : interpreted and executed. ther, © the code of imported module is * dofined fumetions and variables created in the module are now available to the program i. imported module. at * For imported module, a new namespace is setup with the same name as that of the mo ule, Any duplicate import statement for the same module in the same program is ignored by Py thon, inka, by 18 ato 6. The random) function generates a random floating point number in the range 0.0 to 1.0 and randi {function generates random integer between range a to b. To generate random numbers between ran using random), following formula is used : math.random()*(b = a) +a Now if we have following twvo statements (carefully have a look) (i) int( (math.random() * (b-a)+a)) ” (i) math.randint(a, b) Can wwe say above two statements are now producing random integers from the same range ? Why ? Solution. No, their range is not the same. The first statement will be able to produce random integers (say N) in the range a <= N import statement does not require the imported module's name ny, program code because it modifies the namespace of the current program and brings all impor. variables/definitions in it. GLOSSARY ——F Module Nomed independent grouping of code and doto. , 7 Namespace Named logical environment holding logical grouping of related objects. [sow ee Package A directory containing modules and subpackages and some special files, Saltene brary ‘A reusable chunk of code that can be included and used in other programs. Bem ee Scan OR Cote Assignment Ra NR 1 a 3. 4 5. 6. Z. 12, 13, 14, 8. , In which order Python looks for the What is the usage of help( ) and dir( ) functions. TyPE A : SHORT ANSWER QUESTIONS/CONCEPTUAL QUESTIONS What is the significance of Modules ? What are docstrings ? What is their significance ? Give example to support your answer. What is a package ? How is a package different from module ? What is a library ? Write procedure to create own library in Python. What is the use of file _init_.py in a package even when it is empty ? What is the importance of site-packages folder of Python installation ? How are following import statements different ? (@) import x (® from X import * What is PYTHON PATH variable ? What is its significance ? function/module names used by you. (0) from X import a, b, ¢ Name the Python Library modules which need to be imported to invoke the following functions : log() Gi) pow() (i) cos (iv) randint —(@) sqet() [CBSE D 2016 ; 2020C ; 2019 Write the Python statement for each of the following tasks using BUILT-IN functions/methods only : (@ To insert an element 200 at the third position, in the list L1. [CBSE 24] (ii) To check whether a string named, message ends with a full stop/period or not. What is dot notation of referring to objects inside a module ? Why should the from import statement be avoided to import objects ? iG PYTHON LIBRARIES 7 185 rout understand by standard library difference chop what do ¥' of Python ? 8 he between import aud from import statementa, with exaunples. TYPE By APPLICATION Base QUESTIONS eate module fempConversion.py as giver ta Hy. 4.2 tn the 1, Cent avoke the module with two different t chapter tye fr ‘ {wo aifferent types of inuport statements, how would the function call Ue gervent for imported module's fumetions be affected m rements, how would the functic ‘x funetion cheekMain( ) defined in module Allehe as ks.py Is belay used la two different progam. fe program 1 Alichecks.checkMain(3, 'A’) and tn program 2 as checkMatn(4, ‘2 Why are these two funetion-call statements different from one another when the function being invoked rust the same ? isi 4, Given below is semi-complete code of a module baslepy : 3 y # 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. 4. After importing the above module, some of its functions are executed a8 per following statements, Find errors, if any : (@ square(print 3) () basic.div() —_@ basic.floordiv(7.,7) i) div(100, @) (@) basic.mul(3, 5) (f print (basic. square(3.5)) (y) z= basic.div(13, 3) 5. Import the above module basics.py and write statements for the following : (@) Compute square of 19.23 (®) Compute floor division of 1000.01 with 100,23 (©) Compute product of 3,4 and 5. (HHint, use @ function multiple times). . (@) What is the difference between vasic.div(1e@, @) and — basic.div(@, 100) ? Ea” : COMPUTER SCIENCE wiry Pritt H 6. Select the correct output of the code : “python is fun” My I=s.split() s_new= "-". join([1[2]-upper(), 1[1], 1[2] .capitalize()]) print(s_new) Options : (©) PYTHONAS-Fun —(¢) PYTHON-is-Fun (© Python-is-fun 7 Suppose thet after we import the random module, we define the followis Prthon session : (4) PYTHON 5 5, ing Function called gig def eiFE(): % = rendom.random() - random.random() return(x) Whet would be the result if you now evaluate # the Python prompt ? Give reasons for your answer. a the possible outcome(s) executed from the following sininum values that can be assigned to variable NUMBER. ‘STRING = "CBSEONLINE” NUMBER = random.randint(@, 3) code ? Also specify the maximum xy ce wrile STRING[N] !="L* : print (STRING[N] + STRING[NUMBER] + *#", end NUMBER = NUMBER +1 N=Nn-a ENEAIO# (Gi) LEENOFONE © Consider the following onde = import random prin (int( 22+ random.random() *5), end=**) =(4nt( 22+ random.random() *5), end=* * ) print (nt( 28+ random.random() *5), end=** ) print(int( 28 +random.random() * 5)) Find the suggested output options (i) to (@2). Also, write the least value and highest value that cant generated NSHIEFLO# (jo) ECENBEISE GWRWwWB — iy 29 93. 24 95 +. Consider the following code : Smport random print (182 + random.randint(s, 18), end="*) priat (182 + random.randint(5, 18), end=* * ) print (182+ random.randint (5, 18), end=* * ) print (188 + random.randint(s, 18)) (aii) 2324 23 24 (i) 21 2121.21 mee ysinG PYTHON LIBRARIES choir “ * anggested output opti rind the SUBBes! tions (i) to (it). Also, a Sak (iv). Also, write the feast value and highest value that can be fg 102 105 104 105 Gi) 110-103 104 105 .¢ following package (iti) 105.107 105. HO Gn) 5 105 110 Consider tt (iv) 110 105 105 1 music/ _ _Anit_.py formats/ |—— _init__.py |_ wavread. py L_— wavunite.py effects/ |____init__.py echo.py |___ surround. py Top-Level package Subpackage for File format Subpackage for sound effects reverse. py filters/ Subpackage for filters |____init__.py |___ equalizer.py |_— vocoder.py L__. karaoke.py zach of the above modules contain functions play( ), writefile() and readfile() (@) If the module wavwrite is imported using command import music.formats.wavwrite. How will you invoke its writefile( ) function? Write command for it. (@) Ifthe module wavwrite is imported using command from musicformats import wavwrite. How will you invoke its writefile) function? Write command for it 12. What are the possible outcome(s) executed from the following code ? ‘Also specify the maximum and minimum values that can be assigned to variable PICKER. [CBSE D 2016) import random PICK = random.randint(®, 3) CITY= ["DELHI", "MUMBAI", "CHENNAI", KOLKATA") 5 for Tin CITY : for J in range(1, PICK) = print(I, end="") print( ) (i) DELHIDELHI (i) DELHI MUMBAIMUMBAL DELHINUMBAT CHENNATCHENNAT DELHIMUMBATCHENNAT KOLKATAKOLKATA (i) DELHE (jv) DELHE MUMBAT MUMBAIMUMBAT CHENNAT KOLKATAKOLKATAKOLKATA KOLKATA, COMPUTER SCIENCE i. TENCE WITH PYTHoy % TYPE C : PROGRAMMING PRACTICE/KNOWLEDGE BASED, QUESTIONS 1. Write a Python program having following fimetions + remove letter(sentence, letter) (A fanetion with the following signature : This function should take a string and a letter (a8 singlecharacter string) a8 argu np with every instance of the indicated letter removed, For ample returning a copy of that s remove_letter(“Hello there!”, “e”) should return the string “Hilo thr!” Try implementing iL using .eplit() fun (i) Write a fumetion to do the following + Try implementing the capwords() functionality and join( ). Compare the result with the capwi ing other functions, Le, spli(), capitainy () function’s result, ' 2 Create a module lengthconversion.py that stores functions for various lengths conversion eg, * miletokm() to convert miles to kilometer * kmtomile() to convert kilometers to miles + feettoinches( ) * inchestofect( ) It should also store constant values such as value of (mile in [1 mile = 1.60934 kilometer ; 1 feet = 12 inches} Help( ) function should display proper information. Create a module MassConversion.py that stores function for mass conversion ¢g., * kgtotonne() to convert kg to tonnes * tonnetokg() to convert tonne to kg * kgtopound() to convert kg to pound * 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. 4. Create a package from above two modules as this : meters and vice versa). Conversion |— Length L Lengthconversion. py ——— Mass L 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.

You might also like