0% found this document useful (0 votes)
62 views24 pages

Introduction To Python Module Computer Science Class 11th

This document provides an introduction to Python modules, explaining their purpose and how to import them into programs. It covers the concepts of modularity, the structure of a Python module, and specific modules such as math, random, and statistics. Additionally, it details the syntax for importing entire modules or specific objects, along with examples of using the math module's functions.

Uploaded by

spot02009
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)
62 views24 pages

Introduction To Python Module Computer Science Class 11th

This document provides an introduction to Python modules, explaining their purpose and how to import them into programs. It covers the concepts of modularity, the structure of a Python module, and specific modules such as math, random, and statistics. Additionally, it details the syntax for importing entire modules or specific objects, along with examples of using the math module's functions.

Uploaded by

spot02009
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
Introduction to Python Modules cuheenp eaten snes In This Chapter B.A Introduction 8,2 What Is a Module 7 8.3 Importing Modules in a Python Program 8.4 Working with math Module 8,5 Working with random Module 0,6 Working with statistics Module { reference books etc, And, If you recall, all these book types have one thing in common. Confused ? @ 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 units, these are called miodules, Python comes with many preinstalled modules with different types of functionalities, which you can use in your programs, A related term Is library here. A library refers to a collection of modules that together cater to specific type of needs or applications ¢g., NumPy brary of Python eaters to scientific computing needs. In this chapter you will learn how you can import modules in programs and you will also learn to work with some useful Python modules : math module, random module and statistics module, 231 7 83 COMPUTER SCIENCE WITH PYTHON - XI What is a Modul The act of partitioning a program into individual components (known as modules) is called modularity. A module is a separate unit in itself. The justification for partitioning a program is that © it reduces its complexity to some degree and © it creates a number of well-defined, documented boundaries within the program. Another useful feature of having modules, is that its contents can be reused in other programs, without having to rewrite or recreate them. For example, if someone has created a module say earn play different audio formats, coming from different sources, ¢.g., mp3player, fi-radia player, dad player etc. Now, while writing a different program, if someone wants to incorporate ; fm-radia into it, he needs not re-write the code for it. Rather, the can use the f-radio functionality from PlayAudio module. Isn't that amazing ? Re-usage without any re-work - well, that's the beauty of modules. A Python module is a file (_py file) containing variables, class definitions, statements and functions related to a particular task. Figure 8.1 shows the general composition/structure of a Python module. PYTHON MODULE Figure 8.1 Composition/Structure of a Python Module Importing Modules in a Python Program In Python if you want to use the definitions inside a module, you need to first import the module in your program. Python provides the import statement to import modules in a program. ‘The import statement can be used in two forms : @ toimportentire module : _ the import command (2) toimport selected objects : the from import command from a module Following subsections will make the utility of both these import commands clear. ‘Ghopter 8 : INTRODUCTION TO PITHON MODULES 8.3.1 Importing Entire Module ‘The import statement can be used to import an entire module and even for importing selected items. To import an entire module, the import statement can be used as per the following syntax : (please remember, in syntax, | | specify optional elements.) import module1 [, modulez [, ... module} } For example, to import a module, say time, you'll write : import time <—————_ statute nmy time being imported To import two modules namely decimals and fractions, you'll write : import decimals, fractions «—————__ Two mudules namely deciaat and factions being gored with tne ingot wasomert ‘The import statement internally executes the code of module file and then makes it available to your program. The import statement like the one shown above, imports entire module iz, everything defined inside the module — function definitions, variables, constants etc. Alter importing a module, you can use any function/ definition of the imported module as per following syntax : OTE . () Aster importing 8 motte, to access This way of referring to a module's object is called dot notation. ‘specify the name of the module and Le’shavea look at an example module, namely tempComversion _ the name of the function, separated in figure 62. by 2 dot (20 known 25 2 period). (Please note, itis not from Python's standard library ; it is a user ee format scaled dot notation created module, shown here for your understanding purposes). | [Link] |" "Conversion Functions between fahrenheit end centigrade” ~~ } A docaring ; There are tec more decsorings in this tmocule ~ one each brie cack foncsion "* "Retunns: x converted to cen return 5* (x-32)/9.0 def to_Fahrenheit(x): +7 "returns: x: return$*x/5.8+32 — # Constants FREEZING C-0.0 #water freezing temp. (incelcius) FREEZING F=32.0 #uater freezing temp. (in Fahrenheit) Figue 8.2 A semple module ([Link]) For example, consider the module tempConversion given in figure 82 To use its function to_centigradel ), we'll be writing = import tempConversion ‘tempConversion.to_centigrade(98.6)4¢——— Sper mada aplenin ” COMPUTER SCIENCE WITH PYTHON ~ Xt ‘The name of a module is stored inside a constant _name__ (prefix & suffix are having two underscores). You can use it like : Nore import time The name of a module is stored Inside a constant 1 print{tine,_name_) inside a constant _name_, It will print the name of imported module (see below) >>> dmport tine ar >>> print time._name__ Se You can given alias name to an imported module as : import as eg, import tempConversion as tc Now you can use name te for the imported module e.g, teto_centigrade( ). Please nate, if ina module there is another import statement importing an already imported module (from same origin), Python will ignore that import statement: Thus, a module once imported will not - be re-imported even- when another import statement for the same module is encountered again. Processing of import command When you issue import command, internally following things take place : ® the code of imported module is interpreted and executed®. © defined functions and variables created in the module are now available to the program that imported module. © For imported module, a new namespace is setup with the same name as that of the module, For instance, you imported module myMod in your program. Now all the objects of module myMod would be referred as myMod., ¢.g., if myMod has a function defined as checknum( ), then it would be referred to as [Link]( ) in your program. 8.3.2 Importing Select Objects from a Module If you want to import some selected items, not all from a module, then you can use from import statement as per the following syntax : from import [, [...]]* To Import Single Object If you want to import a single object from the module like this so that you don’t have to prefix the module’s name, you can write the name of object after keyword import. For instance, to import just the constant pi from module math, you can write : from math import pi 1. For additional utility of _name__, refer to Appendix C. 2. Refer to Appendix C to stop execution of module's main block while importing. Chopter 8 : INTRODUCTION TO PYTHON MODULES Now, the constant pi can be used and you need not prefix it with module name. That is, to print the value of pi, after importing like above, you'll be writing print (pi) <—— Afr Irom import command yu nea! not quai the name of tnpotd em wth mle name lie ts Not this oT Do not se male name wih imported ‘ ctf impor ecugh Prank (math. PS) Ean ras igo command Do not use module-name with imported object if imported through from import command because now the imported object is a part of your program's environment. To Import Multiple Objects If you want to import multiple objects from the module like ay V2: eee this so that you don’t have to prefix the module’s name, you OnE can write the comma separated list of objects after the Do not use module-name with imported object if imported through ie amaport, from import command For instance, to import just two functions sqrt( ) and pows ) ‘because now the imported object is a from math module, you'll write : ‘part of your program's environment. from math import sqrt, pow To Import All Objects of a Module Ifyou want to import all the items from the module like this so that you don’t have to prefix the module’s name, you can write : from import * That is, to import all the items from module math, you can write : from math import * Now you can use all the defined functions, variables etc from math module, without having to prefix module's name to the imported item name. Processing of from import command When you issue from import command, internally following things take lace : , © the code of imported module is interpreted and executed. . © only the asked functions and variables from the module are made available to the program. © no new namespace is created, the imported definition is just added in the current namespace. Figure 8.3 illustrates this difference. m That means if your program already has a variable with the same name as the one imported via module, then the variable in your program will hide imported member with same name because there cannot be two variables with the same name in one namespace. x COMPUTER SCIENCE WITH PTHON — 11 8.4 Figure 6.3 Difference between import and from impor commands. Following code fragment illustrates this. Let's consider the module given in figure 82 from tempConversion import * FREEZING_C=-17.5 # it willl hide FREEZING _C of tempConversion module print (FREEZING _C) The above code will print -17.5 If you change above code to the following (we made Se FREEZING_C =~ 175 as a COMMENT, see below :) oid using the from tempConversion import * a —_ a 2-17. import statement, it may lead t0 # FREEZING C=-17.5 -# it 4s just a coment now re kn Print (FREEZING_C) , no protlems occur. Now the above code will give result as: 0.0 as no variable from the program shares its name, hence it is not hidden. Working with math Module Other than the built-in functions, Python makes available many more functions through Oiiaios tis stance ion, Python’s standard library is a collection of many modules for different functionalities, eg., module time offers time related functions ; module string offers functions for string manipulation and so on. Python’s standard library provides a module namely math for math related functions that work with all number types except for complex numbers. In order to work with functions of math module, you need to first import it to your program by giving statement as follows as the top line of your Python script : Amport math hen you can use math library's functions as math.. Conventionally (not 2 syntactical requirement), you should give import statements atthe top of the program code. Chopter 8 : INTRODUCTION TO PYTHON MODULES a Following table (Table 8.1) lists some useful math functions that you can use in your programs, Teble 8.1. Some Mathematical Functions in math Module ‘yp (General Form) 4 Prototype Description Example [Link](num) 4. | [Link](arg) 5. [Link] (num) | [Link] (num) ‘[Link] (num) | [Link] (num, [base] ) ‘The ceil() function returns the smallest integer not ‘The sqrt() function returns the square root of num, If num <0, The exp(.) function returns the natural logarithm e raised to the arg power. ‘The fabs( ) function returns the absolute value of mum. ‘The floor) function returns the| largest integer not greater than mum. The log( ) function returns the natural logarithm for num. A domain error occurs if num is negative and a range error occurs if the argument mum is zero. [Link] (1.03) gives 2.0 [Link](61.0) gives 9.0. mash exp (2.0) gives the value of. math fabs(1.0) gives 1.0 |_math.fabs(-10) gives 1.0. math floor (1.03) gives 1.0 math floor(-103) gives -20. [Link](1.0) gives the natural logarithm for 1.0. [Link] (1024, 2) will give logarithm of 1024 to the base 2. Jogi math.Jog10 (num) ‘The 1ogi0( ) function returns the base 10 logarithm for num. A domain error occurs if num is negative and a range error _| occuts if the argument is zero. math logi0(1.0) gives base 10 logarithm for 1.0. math, pow w (base, exp) ‘The pow( ) function returns base raised to exp power i-,. base exp. ‘A domain error occurs if base and exp <=0 ; also if base <0 and exp is not integer. [Link] (3.0, 0)gives value of #, math pow (4.0, 2.0) gives value of 4, [Link](arg) The sin() function returns the sine of arg. The value of arg must be in radians. [Link](val) (val is a number). 10. [Link](arg) The cos( ) function returns the cosine of arg. The value of arg must be in radians. [Link](val) (val is a number). nL. [Link](arg) ‘The tan( ) function reliuns the tangent of arg. The value of arg must be in radians. [Link](val) (val is a number) 2 [Link](x) from radians to degrees. “The degrees( ) converts angle x | [Link](3.14) would give 17991 13, ‘[Link](x) ‘The radians( ) converts angle x from degrees to radians. [Link](179.91) would give 3.14 _ COMPUTER SCIENCE WITH PYTHON - 1 ‘The math module of Python also makes available two useful constants namely pi and e, which you can use as: math.pi__ gives the mathematical constant m =3.141592..., to available precision, mathe gives the mathematical constant ¢ =2.718261..., to available precision. Following are examples of valid arithmetic expressions (after import math statement) ; Given: a=3, b=4, c=5, p=7.0, q=93, r= 1051, x=25.519, y= 10-24.113, 2=231.05 (i) [Link](a /b, 3.5) (ii) [Link](p / q) + [Link](a ~ 4 (ii) x/y+ [Link](p+a/b) (iv) ([Link] (b)*a)-c ——_(v) (mathceil (p) + a)#c —\___ Following are examples of invalid arithmetic expressions : (@) xter two operators in continuation, (i) q(a+b-z/4) operator missing between q and a. (ii) math.pow0, -1) ain error because if base =0 then exp should not be <=0, (iv) [Link](-3)+p/q _Yomain error because logarithm of a negative number is not possible. Write the corresyonding Python expressions for the following mathematical expressio O Veer (i) 2-ye™ +4y tin pv mo r+9) (iv) (cosx/tanx)+x (o) |e? =x] SOLUTION [Link] (aea+ bob + c+) (ii) 2~ ys [Link](2*y) +44y (i) p+g/[Link]((r +), 4) (iv) ([Link] (x) / [Link] (x) ) +x (v) mathfabs ([Link](2) -x) EXAMPLE BA) The radius ofa sphere is 7.5 metres. Write Python script to calculate its area and volume, (Area of a sphere = 4xr?; Volume of a sphere =4/3nr°) SOLUTION import math re7.5 area=4* [Link]*r volune = 4/3 * [Link] * [Link](r, 3) print ("Radius of the sphere :", r, “metres") print("Area of the sphere :", area, “units square") print("Volume of the sphere : ", volume, “units cube") Output : Radius of the sphere : 7.5 metres Area of the sphere : 706.8583470577034 units square Volume of the sphere : 1767.1458676442585 units cube (Chopter 8: INTRODUCTION TO PYTHON MODULES 8.5 Working with random Module Python has a module namely random that provides generators. A random number in simple words means — a number generated by chance, ie., randomly. To use random number generators in your Python program, you first need to import module random using any import command, eg., import random Three most common random number generator functions in random module are : it returns a random floating point number N in the range [0.0. 1.0) random{ } ie, 00< N< 10. Notice that the number with random ) will always be less than 1.0. (only lower range-limit is inclusive). Remember, it generates a floating point number. randint(a, 5) it retums a random integer N in the range (a,b), ie, asNSb (both range-limits are inclusive). Remember, it generates an integer. randrange it returns random numbers from range start_stop with step value. («start>, , ) Number generated is always in range : start < N< stop. Let us consider some examples. In the following lines we are giving some sample codes along with their output 1 To generate a random floal jint number between 0.0 to 1.0, simply use random( ) : oe ting- point ply >>> import random >>> print ([Link]()) The cusps generaned & becswven range 10.0, 1.0! @.022353193431 2. To generate a random floating, point number between range lower to upper using random( ) : (a) multiply random() with difference of upper limit with lower limit, ie, (upper - lower) (®) add to it lower limit For example, to generate between 15 to 35, you may write : >>> import random need not re-write this comand, if randoa module already imported >>> print ([Link]()* (35 -15 ) +15) 2B. 3O7IBT234 ta eau genera is fating pine number benwcen range 15 0 35 3. To generate a random integer number in range 15 to 35 using randint( ), write : >>> print ([Link] (15, 35)) 16 ¢@$ The cuspus generated is ineger bers mange 15 10 35 Using randrange( ) function ‘The function randrange( ) can be used in following three ways : (@ random-randrange() to generate a random number in the range 0 to , eg, following code will generate a random number from 0 to 45 >>> random. randrange(45) 13 + A random monter gneated i he range 0.45 in fact, pseudo-random numbers are generated because it is generated via some algorithm or procedure and hence COMPUTER SCIENCE WITH PYTHON - Xi (i) [Link](>» [Link](11, 45) 25 , , ) to generate a random number in the range to , but here, the difference between two such generated random numbers will be a multiple of value. For example, following code will generate a random number in the range 11 to 45, with a step value 4. That means, the possible random numbers that may be generated will be one of the values 11, 15, 19, 23, 27, 31, 35, 39, 43 >>> [Link](11, 45, 4) a5 39> [Link](31, 45,4) | ¢__ ser each generated random number is 35 one ofthe above given values >»> random,randrange(11, 45, 4) 39 So, internally, randrange with a value creates a series from to with each value at values apart and randomly picks one from this. EXAMPLE [Ey What could be the minimum possible and maximum possible numbers by following code ? import random print([Link](3, 16) - 3) SOLUTION. minimum possible number =0 maximum possible number =7 Because, © randint(3, 10) would generate a random integer in the range 3 to 10 © subtracting 3 from it would change the range to 0 to 7 (because if randint(3,10) generates 10 then -3 would make it 7 ; similarly, for lowest generated value 3, it will make it 0) EXAMPLE EY What will the folowing code produce ? Discuss. import random print ([Link]() * 160) print ([Link]()) SOLUTION The given code will firstly print a random number generated in the range 0.0 to 100.0. And in the next line, it will print a random number generated in the range 0.0 to 1.0. Output can be somewhat like : 77.41547442568118 0.03735925715458066 Every time the code is run, a different output will be printed as different random numbers will be generated. =", CChopler 8 : INTRODUCTION TO PYTHON MODULES EXAMPLE [Bf Write a code fragment to generate a random floating number between 45.0 and 95.0. Print this number along with its nearest integer greater than it SOLUTION import random import math num = random. random( ) * (95 - 45) +45 num = math.cei1( foun ) print ("Random nunbers between 45..95:") print(fnum) print("Nearest higher integer :", inum) Output: random numbers between 45..95 : 48.24212504903489 Nearest higher integer : 49 Exampte [al Write a code fragment to generate two random integers between 450 and 950. Print these numbers along with their average. SOLUTION import random numi = [Link](45@, 950) - 450 nun2 = [Link] (450, 958) - 456 avg = (num + num2)/2 print( "Random integers in the range 45 to 950 :, num1, num2) print("Their average :", avg ) Output = Random integers in the range 450 to 950 : 472 145 Their average : 308.5 EXAMPLE [Write a code fragment to generate three random integers in the range 10, 70 with a step of 13. Create a set with these numbers. SOLUTION import random num = [Link](10, 72, 13) num2 = [Link](10, 70, 13) num3 = [Link](10, 70, 13) set = {num1, num2, nun3} Print( "Random integers in the range 10.70, step-value 13 :", num, nun2, nun3) print("Set created :", set1) Output : Random integers in the range 10..70, step-value 13: 10 10 62 Set created : {10, 62} POUAPLIE SCIENCE YUN PENCE + Working with statistics Module ‘The statistics module of the Python Standard Library provides many statistes funettins sui a» mean{ ), median( ), model } ae, In ordwr to ase ese In your program, you reed ty first import thee Python statiéties module by giving one of the following, statements + Amport statistics «.. sese Moped full siaubetier uote Or from statistics Amport mean, median, node +» Jen wy te Yeni fo ‘ile reli You ean thon use these functions as given below + (i) statistics. mean(eseg®) I return the averayp value of the set/ouquere tf valinen paosud, (ii) statistics, median(>> Amport statistics 999 $0q* (5) 6) 7,5) 6y 5) 5) 9, My 42, 23, 9} >>> statistics mean(seq) 8.25 voy statistice medien(sea) | 4 ar sm; is sl eof lee sop 668 craleulated ising elvis mele >>> statistics mode(seq) 5 EXAMPLE EEL Given a fot containing these values (22, 13, 28, 13, 2, 25, 7, 13, 25). Write ade to ele mean, median and mode of ths Het. SOLUTION Amport statistics as stat Lst1 = [ 22, 13, 28, 13, 22, 25, 7, 13, 25) Lst_meon = [Link](14st1) List_nedian = stat .median(1ist) List_node » [Link](14st1) i print(“Glven List :", 14st1) ! print ("Mean :", List_mean) print(“Median :", 14st median) print(“Hode :", 1ist_node) Output : Given Vist + (22, 14, 26, 23, 22, 26, 7, 33, 25) Mean : 18, 666666666666668 Median ; 22 Mode : 13 Chopier 8 : INTRODUCTION TO FYTHON MODULES EXAMPLE [ol] Have a look at the below given Heron's formula to calculate the arca of a irlangle through tts three sides a,b, and ¢ attPTE pen yh Which Python module would you need to import to calculate area ueing this formula ? Can you use statistics module’ mean() for calculating s in above given formula ? SOLUTION Python's math module should be imported in order to calculate the square root using sqrt() No, we cannot use mean( ) function of statistics module because s is not the mean of a, b and ¢; it is the half of the sides’ sum. or ‘of needs or applications. forms of Import statements ) Import (os ] OTQs i MULTIPLE CHOICE QUESTIONS A py file containing constants/variables, classes, functions etc. related to a particular task and can be used in other programs is called (@) module () library (©) classes (@ documentation 2. The collection of modules and packages that together cater to a specific type of applications or requirements, is called (a) module (8) library (0 classes (@) documentation 3. Which command(s) modifies the current namespace with the imported object name ? (a) import (H) import , (6) from import (@) from import * 4. Which command{(s) creates a separate namespace for each of the imported module ? (a) import (0) import , (6) from import (@) from import * 5, Which of the following random module functions generates a floating point number ? (a) random( ) (b) randint( ) (c) uniform( ) (d) all of these 6. Which of the following random module functions generates an integer ? (a) random( ) (H) randint( ) (6) uniform( ) (@) all of these Re ae COMPUTER SCIENCE WITH PYTHON ~ 10 7. A Python module has ___ extension. (@) mod (6) imp © py (@) .mpy 8. Which of the following is not a function/method of the random module in Python ? {CBSE Paper 2021 (Term 1)) (@) randfloat( ) (b) randint( ) (© random( ) (@) randrange( ) : 9. What will the following code result as ? { import math x=100 i print (x>@[Link]( x) ) (@) True @1 (10 (@ 100 FILLIN THE BLANKS 2 1. To use function fabs( ), module should be imported. 2. To generate a random floating number in the range 0 to 100, __ function is used. 3. To generate a random integer in a range, function is used. 4. To generate a random number in a sequence of values where two values have a difference a step value, function is used. | 5. To use mean( ) function, __ module is to be imported. TRUE/FALSE QUESTIONS 1. A Python program and a Python module means the same. 2. A Python program and a Python module have the same py file extension. 3. Any folder having .py files is a Python package. 4. The statement from import is used to import a module in full. ASSERTIONS AND REASONS DIRECTIONS 1. 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. 2. Assertion. If an item is imported through from import statement then you do not 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 Chapter 8 : INTRODUCTION TO PYTHON MODULES 3. Assertion. Python offers two statements to import items into the current program : import and fromimport, which work identically. Reason. Both import and from import bring the imported items into the current program. Solved Problems 1. 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. 2. What happens when Python encounters an import statement in a program ? What would happen, if there is 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 : the code of imported module is interpreted and executed. defined functions and variables created in the module are now available to the program that imported module. ¢ For imported module, a new namespace is setup with the same name as that of the module. Any duplicate import statement for the same module in the same program is ignored by Python. 3. The random( ) function generates a random floating point number in the range 0.0 to 1.0 and randint(a, b) function generates random integer between range a to b. To generate random numbers between range a to b using random( ), following formula is used : [Link]()*(b - a) +a Now if we have following two statements (carefully have a look) (® int( ([Link]() * (b- a) +a) ) (@ [Link](a, b) Can we say above too 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 in the program code because it modifies the namespace of the current program and brings all imported variables/definitions in it. Given the following Python code, which is repeated four times. What could be the possible set of outputs out of given four sets (dddd represent any combination of digits) ? Amport random print(15 + random, random() * 5) (i) [Link], [Link], [Link], [Link] ii) [Link], [Link]. [Link], [Link] i) [Link], [Link], [Link], [Link] {iv) [Link], [Link], [Link], [Link] Chopler 8 : INTRODUCTION TO PYTHON MODULES Solution. Option (ii) ahd (iv) are the correct possible outputs because : (2) random( ) generates number N between range 0.0 <= N<1.0. (0) when it is multiplied with 5, the range becomes 0.0 to <5 (©) when 15 is added to it, the range becomes 15 to < 20 Only option (ii) and (iv) fulfill the condition of range 15 to < 20. 17. Ina school fest, three randomly chosen students out of 100 students (having roll numbers 1-100) have to present bouquets to the guests. Help the school authorities choose three students randomly. Solution. import random student] = [Link](1, 108) student2 » [Link](1, 100) student3 = [Link](1, 160) print ("3 chosen students are’, ) print(student1, student2, student3) 18. A triangle has three sides a, b, ¢ as 17, 23, 30. Calculate and display its area using Heron's formula as Solution. import math a,b, c=17, 23, 30 s=(at+b+c)/2 area =[Link](s * (s-a) * (s-b) * (s-c)) print("Sides of triangle:", a, b, c) print("Area :", area, “units square") Output : Sides of triangle: 17 23 30 Area : 194.42222095223582 units square ¢ Puidelines to NCERT Questions | [NCERT Chopter 5} | 20. The formula E= mc? states that the equivalent energy (E) can be calculated as the mass (m) multiplied by the speed of light (c= about 310° m/s) squared. Write a program that accepts the mass of an object and determines its energy. > Ans. import math m= float(input("Enter mass : ")) =3* pow(10, 8) E=m*ctc print ("Equivalent energy :",£, "Joule") # unit of energy is Joule Output : Enter mass : 8.95 Equivalent energy : 8.055e+17 Joule COMPUTER SCIENCE WITH PYTHON ~ xi <1. Presume that a ladder is put upright against « wall. Let variables length and angle store the length of the ladder and the angle that it forms with the ground as it leans against the wall, Write a Python progrant to ©) compute the height reached by the ladder on the wall for the following values or length and angle a : (a) 16 feet and 75 degrees (b) 20 feet and 0 degrees 5 (0) 24 feet and 45 degrees (a) 24 feet and 80 degrees Ans, Since the ladder leaning against the wall will form a right-angled triangle, the height up to which a ladder reaches can be hetsino calculated as : ‘Thus, our Python program is based on the same. import math length = float (input ("Enter length of the ladder :")) angle = float( input ("Enter angle of leaning (in degrees) :")) ang_radian = math. radians (angle) convert degrees to radians. height = length * math, sin(ang_radian) print (“Ladder’s height on the wall :", height) Sample run : Enter length of the ladder : 16 Enter angle of leaning (in degrees) : 75 Ladder’s height on the wall ; 15.454813220625093 Enter length of the ladder ; 20 fnter angle of leaning Cin degrees) : 0 Ladder’s height on the wall : 0.0 Enter length of the ladder : 24 Enter angle of leaning (in degrees) : 45 Ladder’s height on the wall : 16.970562748477143 Enter length of the ladder ; 24 Enter angle of leaning Cin degrees) : 80 Ladder's height-on the wall : 23.63538607229299 GLOSSARY oe Chopter 8 : INTRODUCTION TO PYTHON MODULES Assignments TyPe A : SHORT ANSWER QUESTIONS/CONCEPTUAL QUESTIONS 1. What is the significance of Modules ? 2. How are following import statements different ? (@) import X (®) from X import * (9) from X import a, b, ¢ 3. Name the Python Library modules which need to be imported to invoke the following functions : ( log() (i) pow() (iif) cos. (io) randint (0) sqrt( ) {CBSE D 2016 ; 2020 ; 2019} 4. What is dot notation of referring to objects inside a module ? 5. Why should the from import statement be avoided to import objects ? Explain the difference between import and from import statements, with examples. TYPE B : APPLICATION BASED QUESTIONS 1, Consider the module [Link] as given in Fig. 8.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 ? 2. Suppose that after we import the random module, we define the following function called diff in a Python session : def diff(): x = random. random() ~ [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. 3. 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. [CBSE D 2015] 1 ‘STRING = "CBSEONLINE" NUMBER = [Link](@, 3) N=9 while STRING[N] !='L' : ; print (STRING[N] + STRING[NUMBER] + NUMBER = NUMBER + 2 N=N-1 (@ ES#NE#IO# (ii) LEFNO#ON# (il) NS#TEHLO# (io) ECENBAISE wr COMPUTER SCIENCE WITH PYTHON - XI 4 Consider the following code : import random print(int( 2@ + [Link]() *5), end = print(int( 20+ [Link]() *5), end = print(int( 20+ [Link]() *5), end = print (int( 20+ random. random() *5)) Find the suggested output options () to (iv). Also, write the least value and highest value that can be generated. (20222425 (ii) 22.23.2425 (iii) 23.24 23-24 (iv) 2121.21.21 5, Consider the following code : import random print(100+[Link](5, 10), end='* ) print (100+ [Link](5, 18), end =‘ * ) print(1@0 + [Link](5, 10), end='') print(10@ + [Link](S, 18)) Find the suggested output options (i) to (iv). Also, write the least value and highest value that can be generated. ( 102105 104 105 (ii) 110 103 104 105 (iit) 105 107 105 110 (iv) 110 105 105 110 6. 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 ‘[Link](@, 3) ‘DELHI, "MUMBAI", "CHENNAI", "KOLKATA"] ; for TinCITy: for Jin range(1, PICK) : print(Z, end="") print( ) () DELHIDELHT (i) DELHI MUMBATMUMBAT DELHIMUMBAT CHENNATCHENNAT DELHIMUMBATCHENNAL KOLKATAKOLKATA (iii) DELHI (jv) DELHI MUMBAL MUMBAIMUMBAT CHENNAT KOLKATAKOLKATAKOLKATA KOLKATA 7. Consider the code given below = import random r= [Link](100, 999, 5) print(r, end=' *) = [Link](1@0, 999, 5) print(r, end=' *) = [Link](1@0, 999, 5) print(r) Chapter 8 : INTRODUCTION TO PYTHON MODULES 7 Which of the following are the possible outcomes of the above code ? Also, what can be the maximum. and minimum number generated by line 2 ? (a) 655, 705, 220 (b) 380, 382, 505 (c) 100, 500, 999 (d) 345, 650, 110 8, Consider the code given below import random = [Link] (10, 108) - 10 print(r, end =‘ ') = [Link](10, 100) - 16 print(r, end =" ") 7 = [Link](1@, 100) - 10 print(r) Which of the following are the possible outcomes of the above code ? Also, what can be the maximum and minimum number generated by line 2? (a) 12.45 22 () 100 80 84 (101 12.43 (@ 100 1210 9. Consider the code given below : import random r= [Link]() * 16 print(r, end=' ") r= [Link]() * 10 print(r, end ") r= [Link]() * 16 print(r) Which of the following are the possible outcomes of the above code? Also, what can be the maximum and minimum number generated by line 2? (a) 05 16 98 (6) 10.0 1.0 0.0 (c) 0.0 5.6 8.7 (d) 0.0 79 10.0 10. Consider the code given below : import statistics as st v=(7, 8,8, 11, 7,7] m1 = st-mean(v) m2 = [Link](v) m3 = [Link](v) print(m1, m2, m3) Which of the following is the correct output of the above code ? (7 875 (877 (98775 (085775 Type C : PROGRAMMING PRACTICE/KNOWLEDGE BASED QUESTIONS 1. Write a program whose three sample runs are shown below : Sample Run 1 : Random number between 0 and 5 (A) : 2 Random number between 0 and 5 (8) : 5. A to the power B = 32 COMPUTER SCIENCE WITH PYTHON - XI Sample Run 2: Random number between 0 and 5 (A) : 4 Random number between 0 and 5 (8) A to the power 8 = 64 Sample Run 3 Random number between 0 and 5 (A) Random number between 0 and 5 (8) A to the power B = 1 Write a program that generates six random numbers in a sequence created with (start, stop, step). Then print the mean, median and mode of the generated numbers. Write a program to generate 3 random integers between 100 and 999 which is divisible by 5. Write 2 program to generate 6 digit random secure OTP between 100000 to 999999. Write a program to generate 6 random numbers and then print their mean, median and mode. 6. Write a program to calculate the area of an equilateral wiangle (area = * side * side) 1 ty p 4 7. Write a program to computer (a+ b)* using the formula a* +0? +.

You might also like