0% found this document useful (0 votes)
25 views

Functions Ch2

Uploaded by

Prince
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)
25 views

Functions Ch2

Uploaded by

Prince
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/ 11
2, State whether the following statements are True or Fals (a) A library in Python is a collection of various packages. (b) Modules are used to categorize Python code into smaller parts. (c) The docstrings are useful for compilation of the code. (a) Python uses namespaces for documentation. (e) Module aliasing is carried out by using the as keyword. (f) Python does not allow creating own packages: (g) A library can have multiple modules in it. (h) Modularity increases the complexity of a Python program. ()) A package in Python must hold the file __init_.Py: () A package and a library are technically not the same. Answers: (a) True (b) True (c) False (d) False (e) True (g) True (h) False (i) True (i) False 3, Multiple Choice Questions (MCQs) {a) What will be the output of the following Python code? from math import factorial int (math. factorial (5)) (i) 120 (ii) Nothing is printed (ili) Error, method factorial doesn’t exist in math module {iv) Error, the statement should be: print(factorial(5)) (b) What is the order of namespaces in which Python looks for an identifier? (i) Python first searches the global namespace, then the local namespace and final namespace (ii) Python first searches the local namespace, then the global namespace and finall namespace (ili) Python first searches the built-in namespace, then the global namespace and fi namespace ‘ (iv) Python first searches the built-in namespace, then the local namespace and fina namespace (c) Which of the following is not a valid namespace? (i) Global namespace (ii) Public namespace Built-in namespace {iv) Local namespace (d). What will be the output of the following Python code? #modulel ‘3 def change (a): : b=[x*2 for x ina] e print (b) #module2 3 def change (a): ag b=[x*x for x ina] print (b) from modulel import change ae from module? import change main s=[1,2,3] = change (s) (i) (2,4,6) (ii) [14,9] (iii) (2,4,6) 1149) (iv) There is a nar random.choice('sun') (iy sun 1) what possible OUtput(s) are expected to be (7 rogram from the following code? °* “Pl (ii) either s, Worn (iv) error ved on screen at the time of execution of the t random 0, 30, 40, 50, 60, 70] dom. randint (1,3) randint (2,4) n range (FROM, T0+1) print (AR[K],end=" 4m) () 10840870% (ii) 30Ha0%s0% (ii) Sonsow70% (iv) 4080870" {g) Which ofthe statements Is used to import all names from a module into the current calling module? i) Import (ii) from (iil) import * (iv) dir) (h) Which ofthe variables tellstheInterpreter where to locate the modiuleflles imported nto program? (i) local i) import variable ii) PYTHONPATH (iv) current (i) Which of the following date class function returns the current system date? ( day) (ii) today() i) month() (iv) yeart) (i) What is the range of values that random.random() can return? ( (0.0, 1.0) (ii) (0.0, 1.0) (i) (0.0, 1.0) (iv) 10.0, 1.0) Answers: (a) (iv) (b) (ii) (© Wi) (8) tiv) (e) (i) (9 i (e) (i) th) (i, OC} 0 ww SOLVED QUES TIONS 1 Python has certain functions that you can readily use without having to write any special code. What types of functions are these? ‘Ars. The predefined functions that are always available for use are known as Python's built-in functions ‘Examples of some built-in functions are: len(), type(), int(), input), ete. 2. What isa Python module? What isits significance? ’Ans, 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 be easily used. ater. Modules can be “imported” in other programs so that the functions and other definitions in imported modules become available to code that imports them. 3. What are docstrings? How are they useful? Ars. &docstrngis just a regular Python triple-quoted string thats the frst thing ina function body/a module/ ® class, When executing a function body (or a module/class), the docstring doesn’t do anything like comments, but Python stores it as part of the function documentation. This documentation can later be {splayed using the help() function. So, even though doestrings appear like comments (no execution), they are different from comments, 4 What happens when Python encounters an import statement in a program? What would happen ifthere ‘sone more import statement for the same module, already imported in the same program? ‘shen Python encounters an import statement, it does the follow x \\ Code of the imported module i interpreted and executed, "| Oetinedfuncionsandvariables created nthemodulearenow the module, \") Forimported module, anew namespaceis set up witht “0 duplicate import statement for the same module int ue 2, State whether the following 1 statements are True or False: {a) Alibrary in Python isa collection of varios packages. stegoriz (b) Modules are used to cal ' {c) The docstrings are useful for compilation of the code. (d) Python uses namespaces fo is carried 0 {e) Module aliasing is carrie (f) Python does not allow creating own packages (e) Alibrary can have multiple modules in it (h) Modularity increases the c documentation. wut by using the as keyword. (i) Appackage in Python must hold the file _init__PY: i) Apackage and a library are technically not the same. Answers: (a) True (b) True (c) False (g) True (h) False (i) True 3. Multiple Choice Questions (MCQs) {a} What will be the output of the following Python code? port factorial from math print (math. factorial (5)) {120 (ii) Nothing is printed .e Python code into smaller par rts. complexity of a Python program. (d) False (j) False (ii) Error, method factorial doesn’t exist in math module (iv) Error, the statement should be: print(factorial(5)) (©) What is the order of namespaces in which Python looks for an identifier? (i) Python first searches the global namespace, then the local namespace and finally the| namespace (ii) Python first searches the local namespace, then the global namespace and finally namespace (ii) Python first searches the built-in namespace, then the global namespace and finally namespace (iv) Python first searches the built-in namespace, namespace (c) Which of the following is not a valid namespace? (0) Global namespace (i) Built-in namespace (4) What will be the out; 'put of the following P\ #module1 ue def change (a) ; code? be[x*2 for x in a] Print (b) #module2 def change (a): belx*x for x inal Print (b) change (s) 0) 246 (ii) then the local namespace and finally t (ii) Public namespace (iv) Local namespace (14,9) (\v) There is a name clash ) (e) True 3) () a @ dul, The math module is used for math-related functions that Work with al my (i) Math module, The / nd random module? 5. What is the utility of Python standard library's math module ar s need modules, What is a module list? Give at least two reasons why we An: nts, We need modules a . ‘A module is a file containing Python definitions and stateme becill ins. A module is a file c following salient features: 1, Amodule allows code reuse _ 2. Itmakes the “main” program shorter and more readabl 3. Enables clearer code organization Ans id on it 7. Observe the following code and answer the question base ) # the math_operation module def add (a,b): recive fates f substract (a,b): return a - b Fill n the blanks for the following code: 2. math_operation_name__ 3. math_operation.add 1, math _operation # get the name of the module. 2p pe ae utpul i math_ operat. Add 1 ai nt ( sie ae ‘ : : is. 1. input 8. Consider the code given in Q.7 and on the basis of it, com # import the subtr: ‘ 1 # subtract 1 from 2 2. print ( (2, 1) # output = 1 iplete the code given below: function m the math_operation module # Import everything Erom math_operations Print (subtract (2, yy # output: 1 Print (add (1, 1)) # output : 2 Ans. 1, from math_operation import subtract 2. subtract 3, import all statement, Ai ven con't maintain that modu” YO" €2P overwrite funstohs and this can be dangerous, 41. What is PYTHONPATH variables om Ans. PYTHONPATH isthe variable thi cio at tells th Hence, it must include 10 source code, You can manually " you create your own package in Python? 42. row © hat @ package May contain subspacka os. We Kno package of OU OWN, We create a dire i you share global variables across modules? 3 for modules within a single pro (Hors) Moths for modu rogram, we create a special module, th : pepper al module, then import the config module modules of ou" applation, Ths ets the module be global tne reat comma satis a Python module? .W 4 madule isa script in Python that defines import statements, functions, el ms AM : fements, functions, classes, and variables. I aso pods executable Python code. ZIP files and DLL files can be modules too, The module holds is nome ng that is in a global variable, - 3 mespace in Python? 15.0 python, every name has a place where it resides and can be looked for. This is known as namespace. it «like @ box where a variable name is mapped to the object placed. Whenever the variable is searched, will be searched to retrieve the corresponding object. es gs, what are the rules for local and global variables in Python? {Hots} variables thatare only referenced inside a function are called implicitly global. Ia variables assigned ww value anywhere within the function body, itis assumed to be a local. a variable is ever assigned a new aside the function, the variable is implicitly local and you need to explicitly declare it as ‘globa. odule’ and ‘package’. {Hors} Python program file is a ‘module’ which imports other modules like ‘objects’ and ‘attributes’. con program folder is a ‘package’ of ‘modules’. A package can have ‘modules’ or ‘sub-folders’ 4s, why is 8 banner saying “RESTART” always displayed in Python module/program execution? Ans. When you execute a program from the IDLE Editor, the interpreter gives a banner saying “RESTART”, meaning that all the things you defined in any shell session so far are wiped clean and the program you running starts afresh rx inal di import change 2 import change Note: Both the modules mod1 and mod2 are placed in the same program, 2) (24,6) (b) (14,9) (9 (24,6), (1,4,9) (4) Thereisaname clash ‘Ans, (4) i, same identifier become part of the ©planat it entities with the ‘blanation: A name clash is when two different ane ee 20, ,,n* *<0P8. Since both the modules have the same function name, 1. Which of ules? ich ofthe following isn’t true about main modul a (8) When a Python file is directly executed, it's considered main module of Progra (©) Main modules may import any number of modules (<) Special name given to main modules is: _main_ “ i Other main modules can import main modules. * (d) les. planation: Main modules are nat meant to be imported into other modu ic ofthese defitions correctly descr, ee ribes & mod () Denote pe ates for roving tana? occas the specification ore SPecIISFUReHonaiiernat eal PROMIARY alata (e) Defines the specication of how istobe usey, 7 ee l™etBOrated nto a prog: (a) Any program that reuses code ee ) Explanation: The term into a program module” refers ‘othe implementation of specific Specific functional lity to be incorporated Which of the following is not an advan Be Of using modul (a) Provides a means of reusing progr ee am code (b) Provides a means of dividing up tasks (c) Provides a means of reducing the sizeof (@) Provides ameans of testing individual p © Explanation: The total size of the program r not, Modules simply divide the program, What is a module, package and a library? Module: A module isa file with some Python code Package: A package is a directory that contains sub. files such as _init__py. brary: A Python library isa reusable chunk of code that is used in program/script usingimport command A package isa library if its installable or gets attached to site-packages folder of Python installation The line between 2 package and a Python library is quite blurred and both these terms are often used interchangeably. the program, arts of the program ‘mains the same regardless of whether modules are used or and is saved with a .py extension, Packages and modules in it along with some special . What happens when Python encounters an import statement in a program? What would happen, ifthere Sone more import statement for the same module, already imported in the same program? When Python encounters an import statement, it does the followin + The code of imported module is interpreted and executed + Defined functions and variables created in a module are now available to the program that imported module + For imported module, a new namespace is set up with the same name as that of the module. Generates a random floating point numberin the range. Any duplicate import statement for the same module in the same program is ignored by poe. What posit Qu ected to be displayed on screen at the time of execution ofthe program ‘om he lowing code as spect the maximum alas that can beasignedto ech fhe vars FROM and To. import random (20, 30, 40, 50, 60,70) FROMrandom.xandint (1, 3) TO-random. randint (2/4) for K in range (FROM, TO+1)# Print (AR(K],end="#")7 (2) 108408708 (9 504608708 * (b) 308408508 Maximum value FROM, TO is (3, + Consider a module ‘greeting’ ‘module greeting. py def greet_msg(): urfactorial (n-1) nter a number: ") ) Y, factorial ne ("8 Goes not exist fos niyaecyy jumbers") print ("The factorial of 0 is 11) t ("The factorial of", num, my 8", recurfact rial (num) ) Rot recommended? ctioned variable to be used is from global environment/scope e '¥s alscouraged as with this programmers tend to lose control over When is a global statement used? Why is its use ans. A global statement is used when the me The use of global statement is alwa variables and their scope. 38. Write a aa in Python to find and display the prime numbers between 2to N. Pass Nas argument to the metho [Dethi 2016] nd the prime numbers between 2 andN meAll (N) : ime nos. between 2 and N") ge (2, N+1): #to iterate between 2 to N+1 i in range(2, num): #to iterate on the factors of the number if num i==0: #to determine the first factor j=num/i #to calculate the second factor break #to move to the next number else: felse part of the loop #loop fall through without finding a factor print (num, end="\n" 38. Write definition of a method ZeroEnding(SCORES) to add all those values in the list of SCORES, which are ending with zero (0) and display the sum. [Delhi 2018) For example, If the SCORES contain [200,456,300, 100,234,678] The sum should be displayed as 600 nding (SCORES) : Zero=0 for i in SCORES if i810 SZero=SZeroti print ("Sum of numbers ending with zer¢ 1. What is Python library? Explain with example. 2 Write a program to calculate the following using (@) Energy=m*g*h cy Wa (9) Speed = distance / time aa 3 Write a module to input total nul after months, and display it in ano’ 4. Write a Program to calculate the 'M one complete package. Volume = 41x r? and Surface Area : ‘What is a module? What is the f a tt” her? mm one anot he following two statements different fro 8. How are tt (a) Import math (b) From math import * 9. What is the utility of math module? ifier? the scope of a name or identifier: 10. How does Python resolve 11, Find the output of the following: import math print (math. floor (5.5) 12, Rewrite the f Python ter removing all syntax error(s). Underline the corre | syntax error(s). Und : the following Python code after removing all sy = input (‘enter any radius:') q A -pi * maths.pow (1,2) Print ("Area = “ta) Main () fe 13. What is the significance of assigning namespace to Python modules? 3 114. How are packages and modules related to each other? 7 415. What isthe difference between import statement and from import statement? : 16. Why is from import * statement not recommended for importing Python modules in program? ; 17. What i a library? ; 18. What is the importance of site-package folder of Python installation? 19. How are the following import statements different? lect (6) -fromXimport* {c) from Ximporta, b,c 20. Name the Python library modules which need to be imported to invoke the following functions: {a (a) log() (b) pow() ‘What is dot notation of referring to objects inside a module? 22. Why should the from import statement be avoided to import objects? Ty of Python? 24. Explain the difference between import

You might also like