You are on page 1of 18
‘ag Whats a Library ? ‘45 importing Modules in a Python Program ‘44. Using Python Standard Library's Functions and Modules 45 creating a Python Library INTRODUCTION ‘You all must have read and enjoyed a lot of book: books etc. And, if you recall, all these book type Don’t be ~all these book types are further divided into chapters. Can you tell, why is this done ? Yeah, you are right. Putting all the pages of one book or novel together, with no chapters, will make the book boring and difficult to comprehend. So, dividing a bigger unit into smaller manageable units is a good strategy. Similarly, in programming, if we create smaller handleable gyre units, these are called modules, A related term is library here, A story books, novels, course-books, reference have one thing in common. Confused ? Q library refers to a collection of modules that together cater to A nese i type of needs or applications ¢.g., NumPy library of sone font Ee caters to scientific computing needs, In this chapter, applications epi We shall talk about using some Python libraries as well as iting own libraries/modules. ANCE wiry . ; ) based on given string or character split strings as members word> ) ~ replaces a word or part of the Letus understand and use these string functions practically. Carefully go through the examples Of these as given below joint ) SSP) I the string based iterator is a string then the is inserted after every character of the s points. I ndgits is not given, it returns nearest inte to its input ym, “converted to integer in2 ways as", tnun, “and”, ra) (rum, 3) loff to 3 places after decimal is, rnum2) mamber eg, “1295 can be converted to munber 12355 COMPUTER SCENCE YH rng, = “este. splitQ) | @ If you do not provide any argument to split hen bby default it will split the pi ‘considering whitespace as a separator, <8 iy ‘>>>"T Love Python” .split() ‘ Wh or without whtpce. th Love’, "Python ne _ sete te at contig i th, Love Python”. split("") mg | 5 “Python | (@ If you provide. string or character a8 an argument © . | ee eats cation tie sven sneer (oF Oe Sing isnot i lit strings © para symbol based string after eac ‘Sing from encrypted Sing. “4-2. Wie a progam that inpss 2 main sing and chen hy character. The program shot ssaseasrasiasnass et Dooce Nae ot cer oma rantort ) will abwrays be les "eel sone Neb fora ba i pesies:. i Peers any eed ee tom rng, nmr the ouput “Topmentes random loting point number between 0.0 to 1.0, simply use random) 99> import random Teer peed re rn 1010) random fotng point amber been rngelocer to upper wsng nde) andor) with diference of upper limit with lower Limit i, (pper= is inportant for learning how to se Ubraries. At is generated via some algorithm or procedure and hence detest | number in the ranges 11.55 or 111_55, after "port statement, you may write stement, you may write = ‘s repeated four times. What could be the possible set of outputs y combination of digits)? are the correct possible outputs because ber N between range 0.0.<= N«< 1.0. the range becomes 0.0 to <5 range becomes 15 to < 20 yndition of range 15 to < 20. 1 possible and maximum possible numbers by following code ? -3) Solution. — minimum possible number =O i ‘maximum possible number =? mm * lle by simply giving their name $s savy ZABCDEFGHTIKLMNOPQRS TUVRY2 Boose onesie te ; 7 © hen —Swoukd mabe 7 panned ae ot rer sme and passing the string name as its Pea nodules be ote that ike other Pie ering mele, you must import pmport string = math and random. rent modules i.e, .py files) to be also be stored in the folder, even COMPUTER SCIENCE wy hoy and spac yon PTHON UBEARES one or more PACKIES "brary in Python ‘ brary can B3ve ate your own It om a ow you can eens 7 e shall be creating simple brag 2 apace + Coa — Natnpeone Pnettoy Dey ies xp Devcon iets Oy semana [Pyuestey pe > iseanooucage Without the Ose Saar ae Jook for subr [2 Mods.py aa 2 itp A package vs. folder | 4.5.2 Procedure For Creating Packoges In order to create a package, you need to follow a certain procedure as discussed below, Major steps to create a package are = 1 Decide about the basie structure of your package. It means that you should have a dear idea about what will be your package's name (ie, a directory/folder tunderscore-sepaated don't The Many ‘ther sys. ;portant information about PYTHONPATH, which tsps el thes) oa Python interpreter will look in when importing instance, we are going to create the ee package shown on the right | pie tof print(sys.path) command, you will find that the paseeniry Tt means that the Python interpreter will frst look in curren when trying to do an import. If the asked module/package is not rectory, then it check the directory listed in PYTHONPATH. ne PTHON UBPARES 175 Scere ge or a fle named iafOF8 {vert ris variable wri! Foy ‘aiable ayspaths TMs Tor input script (or the curr specified) le IPATH (a list of directory names: with the | © variable PATH). by iondependent defaul 5. Ater copying yun package folder in sit on become a Python libra ly Subjects List( ist() and CSX1 module "The site-packages is (p To imp import command as an one eee are wel for documentation purposes sei be pei ren inn eae Ou Type Questions 1 OT related to a particular task and can CREATING AND 1G PA (documenta specific type of applications or (@) documentation mntaining documentation related (@) docstrings Let Us REVISE ’ — hic = oe. Fython community, Pacape son we COMPUTER Sci : aflder to be used as 2 Python package ? 1. Which fle mast bea part of afer EET kage py (4) mate py peer LT re extension. 10. A Python ha ory @ mpy (a) mod @) imp Fai ge putt enn ry eo ” treated as importable package. : lt ater ert a bles, class definitions program. 44 Any folder having py files i a Python package | 5 Aflderhaving py files along witha special file ie, _init_py initis NOTE ¢ Answers for 0TOs are given at the end of the book. Solved Problems 1. What ise module, package and a library ? an importable Python pag. 2. What isa Python module ? What is its significance ? Solution. A “module” isa chunk of Python code that exists in its own ( intendedtabe tath-sqrt() function only “quoted string that isthe firs thing in a function rem ? What would happen there i ‘he same program ? the following ted "ow available tothe program that same name as tha ofthe module Program isignoted by Python. the range 0.0 to 1.0 and rant, b) erate random numbers beeen range ato b look) integers from the same range ? Why ? COMPUTER SCIENCE wiry, pean La 94 (whens et)! we between range 2.4, which is then ra Bet ee anyone you ike =) ree: 4, 9.06 16, om print (e102) of exceution ofthe program fom the each ofthe variables FROM and TO. det 2160 seoltings put scolding is not good 3-7" " 1 soseme print set Lost") | count 30 ssessople”) or scolding 15 ai } er ‘is matale, The code tsi SLY note program Test fe le functions) to this package folder om? Can't we use it without doing so? the package and its contents must be the default place from where Python “And printsimple count) statement causes OUP 10 ould be the outpat produced by the following code import math import random print(wath.ceil(randon.randon())) . 9. What number in the range [0.0, 1.0) but matical) this range. Thus _print(ste( int( math. pow( random. ’ (str( int( math. pow( random. COMPUTER Science CE wm ~~ ee sa situation when two different engi * Solution. There isa nameciash. A name dash © a cea par of the same Since both the modules have the Same function nth coatcee oy 15. What the pole in the ling ef de? ; Fronnath seport factorsal print (ath. factorial(S)) ; foum of impor, the pore identifier (in thi Solution. In the “froarimport” Beats ed's races are fang “Thus the statement should be Pest “ with the module name. prime(factorial(5)) GLOSSARY A) (@ baste. floordiv(7.0, 7) -mul(3, 5) () print (basic.square(3.5)) () Compute floor division of 1000.01 with 100.23 (Hint use a function multiple times). ees odue, we define vdon() = rondon-random) result if you now evaluate 7. What are the possible outcome minimum values that STRING = "CBSEONL ‘unser = random. neo hile STRING|? print (STRING{N] + STRING[NUMBER a) rw", end = '*) GP ESNEMOF (DLENOIONE (G)NSITEFLOF (ir) ECINBHISE |& Consider the following code Anport randow print(int( 20 + random. random (20 + random .randon( print(int( 22 + random. ran Find the suggested output options ae 3 in range, PICK) ata print(I, er ) nu bm pears () DELHIDELHT MUMBAIMUMBAT CCHENNATCHENNAT KOLKATAKOLKATA 19, Consider the following code = (ii) DEL MuneAr CCHENNAT KOLKATA 2 iable PICKER, Top-Level package Subpackage for File Format Subpackage For sound effects Subpackage for Filters mats wavwrite, How will formats import wavwrite. How following code ? Also specify the maximum and [case D 206) (i) DeLAT HIMUMBAL DELHIMIMBATCHENNAT (io) OeLAT MMBAIMUMBAT KOLKATAKOLKATAKOLKATA, COMPUTER Scitnice Ew Pm Mg oy Type C : Programming Practice/Knowledge based Questions 1. Write a Python program having following, functions (A function with the following, signature remove_letter(sentence, letter) This function should take a string and a letter (as a single-character strin returning a copy of that string with every instance of the indicated lette reat a a remove letter(“Hello there!”, “e”) should return the string “Hilo thy For. ea Try implementing it using, .split( ) function. (ii) Write a function to do the following Try implementing the capwords() functionality using other functions, ie, spy and join( ). Compare the result with the capwords( ) function’s result » eta, 2 Create a module lengthconversion py that stores functions for various lengths conversion, to convert miles to kilometer “@, + miletokm( ) 4 kantomile( ) to convert kilometers to miles 4 feettoinches{ ) + 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 ersion eg, 3. Create a module MassConversion.py that stores function for mass conv 4 kgtotonne( ) to convert kg to tonnes 4 tonnetokg( ) to convert tonne to kg 4 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. 4. Create a package from above two modules as this Conversion Length Lengthconversion. py Mass | massconversion.py Make sure that above package meets the requirements of being a Python package. Also, you shad ® able to import above package andjor its modules using import command. 3

You might also like