Download as pdf
Download as pdf
You are on page 1of 126
CLASS XIl Model Test Papers SUMITA ARORA DHANPAT RAI & CO. (Pvt.) Ltd EDUCATIONAL & TECHNICAL PUBLISHE Scanned with CamScanner unit L Programming and Computational Thinking (Part A) A This Unit Chapter 1 Chapter 2 Chapter 3 Chapter 4 (For Examination Question No. 1, 2) Python Revision Tourel Python Revision Tour-Il Working with Functions Using Python Libraries YouTube :Notion Tube Scanned with CamScanner — GF MOVE FAST WITH COMPUTER SCIENCE (Python) ~ XI! GLIMPSES Actual Argument. Argument ++ Actual Parameter. Argument +> Argument. A value provided to a function in the function call statement. + Block. A group of consecutive statements having same indentation level. + Coercion. Implicit Type Conversion. > Constant. A data item that never changes its value during a program run, + Dictionary. A mutable, unordered collection with elements in the form of a key:value pairs that associate keys to value. ~ Empty statement. A statement that appears in the code but does nothing, +> Explicit Type Conversion. Forced data type conversion by the user. + Flow of execution. The order of execution of statements during a program run, + Formal Argument. Parameter ~ Formal Parameter. Parameter + Function, Named subprogram that acts on data and often returns a value. 4 Identifier. Name given by user for a part of the program. + Implicit Type Conversion, Automatic Internal Conversion of data type (lower to higher type) by Python. : + Index. An integer variable that is used to identify the position of an element and access the element. + Keyword. Reserved word having special meaning and purpose. + Lexical Unit. Other name of token. ~ Library. A reusable chunk of code that can be included and used in other programs. + List. A mutable sequence of Python that can store objects of any type. + Literal, Constant. + Lookup. A dictionary operation that takes a key and finds the corresponding value. 4 Mapping. Linking of a key with a value through some internal function (hash function). + Module. Named independent grouping of code and data. 4 Namespace. Named logical environment holding logical grouping of related objects. + Nesting. Having an element of similar type inside another element. + Operator. Symbol/word that triggers an action or operation. + Package. A directory containing modules and subpackages and some special files. ; + Packing. Creating a tupie from individual values. + Parameter. A name used inside a function to refer to the value which was passed to it as an argument. Scanned with CamScanner LNT: PROGRAMING AND COMPUTATIONAL THINKING (Port A) 3 4 Scope. Program part(s) in which a part era ch a particular piece of code ora data value (e.g Variable) can be 4 Sorting. Arranging elements of a sequence in some order (ascending/descending), 4 Token, The smallest individual unit in a program, , 4 Tuple. An immutable sequence of elements, 4 Type Casting. Explicit Type Conversion. 4 Unpacking. Creating individual values from a tuple's elements, + Variable. Named stored location whose value can be manipulated during program run, EF A OBJECTIVE TYPE QUESTIONS Multiple Choice Questions 1. Is Python case sensitive when dealing with identifiers ? La) yes (b) no (©) machine dependent (@) none of the mentioned | 2. Which of the following is an invalid variable ? (@) my_day2 (6) 2nd_day (0) Day_two @2 3) Which of the following is not a keyword ? (a) eval (b) assert (c) nonlocal (@) pass 4, Which of the following is an invalid statement ? (@ abc = 1,000,000 (b)ab (0 a, b, c = 1000, 2000, 3000 @a- = 1,000,000 | 5. Which of the following cannot be a variable ? | YK init @in @it (@on 6. Which of these is not a core date t type ? (a) Lists (®) Dictionary () Tuples (@) Class 7. Given a function that does not return any value, what value is thrown by default when executed in shell ? (a) int (b) bool (9 void (@) none 8, Following set of commands is executed in shell, what will be the output ? >>>str= "hello" >oostr[ :2] >>> @ he (®) lo (0) olleh (a) hello Scanned with CamScanner 4 MOVE FAST WiTH COMPUTER SCIENCE (Python) ~ Xi 9. In Python we do not specify types, it is directly interpreted by the compiler, so consider the following operation to be performed. >>> x= 33 4 What would you fill in place of in above expression so that x has an Anteger value ? Select all that apply (Python 3.xx) 7 LoL o/ (c) % (@) All of the mentioned 10. Which type of error occurs when you execute the following code fragments ? (a) SyntaxError —_(b) NameE ror (9 ValueError (A) TypeError [For your reference : SyntaxError : Occurs when some Python language rules are violated. Occurs’ when Python tries to use a variable or function name, which is not defined before. Occurs when the content of the object being assigned is not of required data type. Occurs when there is attempt to call a function or use an operator on something of the incorrect type.] NameError : ValueErr0} TypeError : >>> fruitl = apple >>> 1=6 >>> tabe' +4-4 >>> al=2 >>> al2+1 (o) >>> int("21.23") 11. Carefully observe the code and give the answer. def function1(a): asat't' asat2 >>>function1 ("hello") (a) indentation Error (®) cannot perform mathematical operation on strings (0) hello2 (@) hello2hello2 12. What data type is the object below ? L=[2, 23, ‘hello', 1] (@) list (® dictionary (© array (@) tuple 13. What data type is the object below ? Lea, 23, thello', 1 () list (b) dictionary (© array (@) tuple Ma! Tube :Notion Tube Scanned with CamScanner 14. 15. 16. 17. 18, 19. 20. 21. 24, YouTube.Noation..ube . To store values in terms of key and value, what core data type does Python provide ? (a) list (b) tuple (0 class (@) dictionary Which of the following statements will print the following ? hello-how-are-you (a) print(‘hello’, ‘how?, ‘are’, ‘you?) (b)print(‘hello’, ‘how?, ‘are’, ‘you? + *-"* 4) (€)_print(‘hello-’ + ‘how-are-you” ) (d)_print(‘hello’ + ‘+? + ‘how’ +‘? + fare’ +=? + ‘you") How would you write x in Python as an expression ? (a) xy “xy (xy (@ none of the mentioned Which one of these is floor division operator ? (@/ —) Il (© % (@ None of the mentioned What is the value of this expression: 22 % 3 is? (a)7 lb) 1 (10 ae (a) 7.0 What is the value of this expression : 22% 3.0 is ? @7 1 10) 10 (70 What is the output of this expression, 3°13 ? (a) 27 9 (3 @1 What is the value of this expression, 313 ? (27 9 (3 @1 What is the value of this expression 3°*3"*1 ? (27 o> 3 @1 What is the value of this expression, 3°3"*1 ? (a) 27 9 ©3 @1 What will be the value of the expression ? 14413%15 (4 (27 (912 @o Evaluate the expression given below if A=16 and B=15. ARB//A (a) 0.0 wo (910 @1 What is the value of x ? x= int(13.25 + 4/2) (a) 17 Ou (9 15 @23 Scanned with CamScanner a 2 30. 3 32. 33. 34, 35. B 36. g 37. - Which of the following statement prints the MOVE FAS WITH! COMPUIER SCIENCE (Python) What is the value of the following expression ? 343.00, 3*93.0 (@) (6.0, 27.0) (®) (6.0, 9.00) (0) 6 27) (@) (6.0, 27.0] (©) 16, 27) The expression 8/4/2 will evaluate equivalent to which of the following expressions : (a) 8/(4/2) (b) (B/AY/2 What is the value of the following expression ? 21//4 + 6/3 @7 ) 7.0 (9) 7.25 (@) 7.33 What is the output of the following expression ? print(4.00/(2.0+ 2.0)) (a) Error (b) 1.0 (c) 1.00 (d)1 Which of the following expressions involves coercion (implicit type promotion) when evaluated in Python ? ()53+18 (99 *41 (45 %3 (@) 71-36 What will be the output of the following expression ? 24//6%3, 24//4//2, 48//3//4 (@) (1, 3, 4) © 0,3, 4) (© Q, 12, ferror) — (d) (1, 3, terror) Which among the following list of operators has the highest precedence ? tee Is ce, >>, | (a) <<, >> o* ©! (a) % What is the output of the following expression ? float(5 + int (4.39 + 2.1)%2) (a) 5.0 5 (9 80 (8 Which of the following expressions is an example of type casting ? (@) 4.0 + float(6) (6) 53 +63 ()5.0+3 (@) int(3.a) +7 Which of the following expressions results in an error 2 (@) float(‘12’) (6) int(‘12") (©) float(‘12.5") List AL is defined as follows i AL=[1, 2,3, 4,5] Which of the following statements removes t list AL equals [1, 2, 4, 5] 2 (a) del af2] (6) af2:3] = [ ] (0) af2:2) =[ @) a2] =[] (© aremove(3) @) int12.5') the middle element 3 from it so that the shown, Output below ? hello\example\test txt @ Print(“hello\ example test.txt”) ©) print(“het ” © Print("hello\“example\ “tes.txt”) nae SEPe testo”) ® Prit(“hello”\example” test. nt”) Scanned with CamScanner UNIT L PROGRAMMING AND COMPUTATIONAL THINENG (Pot 7 39, Suppose s is assigned as follows : s = 'foobar’ [All of the following expressions produce the same result except one. Which one ? @ st 2-5) iD Utes -5} (©) sls -TIL-1] + sflents)}1] (sl) + st-1 (st 5] 40. Which two lines of code are valid strings in Python ? (a) This is a string (b) ‘This is a string’ (6) (This is a string) (d) “This is a string” 41, Which line of code has the correct syntax for the print statement ? (@) print({ts’ a rainy day) (b) Print(it’s a rainy day’) (6) print(it’s a rainy day”) (@ print(it\’s a rainy day’) 42, You have the following code segment: print (“Here we have a Line of text \n and \n we can do \newlines!”) What is the output of this code ? (a) Here we have a Line of text and we can do newlines! (b) Here we have a Line of text and we can do newlines! (Here we have a Line of text and we can do newlines! (@) Here we have a Line of text and we can do ewlines! 43, Which value type does input( ) return ? (@) Boolean () String (©) Int (@ Float 44, You have the following code segment : Stringt = "ay’ String? = "work" print(Stringl , String2) What is the output of this code ? (a) my work (b) work () mywork (a) my 45. You have the following code segment stringt = "ny" String? = "work" print (Stringt + String2) ‘What is the output of this code ? (a) my work (b) work (c) mywork (d) my Scanned with CamScanner 8 MOVE FAST WITH COMPUTER SCIENCE (Python) — Xi 46. You have the following code segment : Strings String2 print(String1 + String2.upper()) ork" What is the output of this code ? (a) mywork () MY Work (o myWorK (@) My Work 47. Which code segment wil (a) myValueos = "10 myValue@2 = "10" myValue@1 = myValueoi + myValue@2 print (myValueo2) output the number 20 to the console window 2 (®) — myValueos = 10 myValue@2 = 10 myValue01 = myValue@t +myValueo2 print (myValueo1) (©) Myvalueoi = 18 myValued2 = 10 print (myValueod + myValuee2) (@) —_Myvalueos = "10" myValuee2 = "10" print (myValueg + myValuee2) Which two operators can be used on numeric values in Python ? @e )% On (et 49. Given the numeric variable Num1, which lines of code properly prints the value ? (a) print(“%d’) () print(“%d”, Numi) (©) print(Num1) (@) print(“%d Numi”) 50. Which operator is used to check whether two variables are the same ? (@)- (== ©! @= 51. Which code segment will NOT reach its print( ) function ? (a) if "yes" t= 'no' : print ("condition met) @_D iF "yes yyes" : _ 2 print (“condition met") (©) if not 'yes* == ‘no’: ~ print("condition met") (d) If "yes* print(“condition met") 52. Which line of code produces an error ? (@) “one” +“twor (6) 142 (9 “one”+"2" (dy 142 Scanned with CamScanner # 28 PRIMING ND SOME TRT DS ERE eer 8 = nat is oe cape of ee ic” pee ROE Oe wr ya" ee & ¥ Winwich Nene of coder wl caver sen semzoee 7 wy ase 3 (ry Lame 2 @imes (@) tame 1 Writat 3s ther sett of tis codie 7 S04 grert_seutie(x) = gree “x gree doula ay ey @t aw Which of dhe isiliownmg four code Segments wil seid aeilewamg autpu: > toe wee Ope ‘Selivet ail of he Sumctem cals Gar vest x his cuter (a) prareg” Eare \awere, \weuta""") @) prdre(-esramiradee***) ©) ordre "ene\emire asia") @) prae("eire 7 Which of the Selling Sour code Sagmemts willl wed dlawing. autre ame ine Dita ‘Select aill of fhe function calls that reswh im, diss cuter (2) pre" Ene w C Scanned with CamScanner 10 YerPereasMetion Tube SS. What will be the output of the following code ? tuple_a='a‘, ‘b* tuple_b=(‘a', 'b') print (tuple_a == tuple_b) Textbook Q. 8, Chapter 2 (Type By) @o (1 (0 False (@) True 59. What will be the output of the following code snippet 2 rec = {"Name" : Python", “Age”: "20", “Addi idi = id(rec) del rec rec = {"Name" id2 = id(rec) {TB Q. 9, Chapter 2 (Type By) "NI", “Country” : "usa Python", "Age": "2@", "Addr" :"No", “Country” ISA") print(idi == id2) (@) True (b) False (1 (@) Exception 60. If retum statement is not used inside the function, the function will return : (@)0 (6) None object (c) an arbitrary integer (@ Error! Functions in Python must have a return statement. [Textbook Q. 1, Chapter 3 (Checkpoint 3.1)] 61. Which of the following keywords marks the beginning of the function block ? (a) fune ©) define (0) def (@ function [Textbook Q. 2, Chapter 3 (Checkpoint 3.1)) 62, What is the area of memory called, which stores the Parameters and local variables of a function call ? (Textbook Q. 3, Chapter 3 (Checkpoint 3.1) (@) a heap (b) storage area ——_(c) a stack (@) an array True/False Questions —— es Mathematical operations can be performed on a string, ‘The expression int(x) implies that the variable x is converted to integer, + The value of the expressions 4/(3%(2-1)) and 4/34(2-1) is the same, The value of the expressions 4/(3%(4-2)) and 4/3*(4-2) is the same. 67. The expression 2%*2"*3 is evaluated as: (22)*3, 68. Do both the following represent the same list”, (lat, 'b', *c") [ct ‘a’, *b') . A list may contain any type of objects except another list, 70. ‘There is no conceptual limit to the size of a list - All elements in a list must be of the same type. A siven object may appear in a list more than once, The keys of a dictionary must be of immutable types, Scanned with CamScanner 81 82. 83, 87. 89. 90. 97. 98, 100, 11 PROGRAMING AND COMPUTATIONAL THNIGIG [Pot A) oT A string can be surrounded by three sets of single quotation marks or by three sets of double quotation marks. Variables can be assigned only once. In Python, a variable is a placeholder for data. You can combine a numeric value and a string by using the + symbol. The clear( ) removes all the elements of a dictionary and also deletes the dictionary. The clear( ) removes all the elements of a dictionary but does not delete the empty dictionary. ‘The max( ) and min() when used with tuples, can work if elements of the tuple are all of the same type. A list of characters is similar to a string type. For any index n, s{:n] + s{n:] will give you original string s. A dictionary can contain keys of any valid Python types. Non-default arguments can be placed before or after a default argument in a function definition. A parameter having default value in the function header is known as a default parameter. The first line of function definition that begins with keyword def and ends with 2 colon ( :), is also known as function header. Variables that are listed within the parentheses of a function header are called function variables. In Python, the program execution begins with first statement of _main__ segment Default parameters cannot be skipped in function call. The default values for parameters are considered only if no value is provided for that parameter in the function call statement. |. A python function may return multiple values. .. A void function also returns a value ie, None to its caller. . Variables defined inside functions can have global scope. A local variable having the same name as that of a global variable, hides the global variable in its function. A Python module has the py extension. Fill in the B The file must be part of the folder holding library files and other definitions in order to be treated as importable package. ‘The smallest individual unit in a program is known as 2 . A token is also called a___. A is a word having special meaning and role as specified by programming language. Lists are types of Python as you can change its values in place. Scanned with CamScanner 12 101 102. 103. 104. 105. 106. 107. 108. 109. 110. 11 112. 113. 14, 115, 116. 117. 18. 119. 120. (MOVE FAST WITH COMPUTER SCIENCE (Python) ~ XI! The data types whose values cannot be changed in place are called _ types, Ina Python expression, when conversion of a value’s data type is done automatically by the compiler without programmer's intervention, it is called The explicit conversion of an operand to a specific type is called The _____ statement is an empty statement in Python. AL following the loop. The statement skips the rest of the loop statements and causes the next iteration of the loop to take place. A is a subprogram that acts on data and often returns a value. statement skips the rest of the loop and jumps over to the statement Python names the top level segment (main program) as___ In Python, program execution begins with first statement of ____ segment, The values being passed through a function-call statement are called ___ ‘The values received in the function definition/header are called __ A parameter having default value in the function header is known as a__ A argument can be skipped in the function call statement. arguments are the named arguments with assigned values being passed in the function call statement. A void function also returns a value to its caller. By default, Python names the segment with top-level statements (main program) as The refers to the order in which statements are executed during a program run. The default value for a parameter is defined in function A refers to a collection of modules that together cater to specific type of needs or applications. A Python is a file (py file) containing variables, class definitions, statements and functions related to a particular task. ANSWERS Multiple Choice Questions 1. @ 20 3 @) 4 o 5 6 7 @ 8. (a) 9% (a), (c) t 10. ( @ Nametirror (apple not defined earlier); (i) (a) Synt Gi) (Ty 2 i Error ; (®) ©) NameError (012 not defined) ; (c) (€) ValueEroe os" Online 1. @ 2 @ B@ . @ B. 7 ® 1% ». © 2. a ° ° Fa i. 23.) 24. 25. (b) 26. (©) 27. (a) 28. ) 29.) 30. () 31. (©) 32 @ aa a be Scanned with CamScanner UNIT L: PROGRAMMING AHO COMPUTANONAL TEIN Yon A) 13 50 3% 37. (38, thy ». Ua oH) a. @) 2d) 43. (by 4. (a) 5. wt 7) 48. (b), (C) 49. (0 50. (by St. thy 52. (ty 3.0 54. (0 55. (a) 56. (0) 57. (a) 3B. (dy 59. (0) 60. (b) 61. (co) 62. (cy True / False Questions 6. F 64. 65. T 66. F oF OF oF 70. T 7. F mT nT “7 nF 76. F 7. OF 78. OF 79.7 wT 81. F 62. T 83. F 4. OF 6. T 6. T 87. F 88. T 89. F 90. T an. T TT 93. F oT 95. T Fill in the Blanks 96. _init_.py 97. Token 98. lexical unit 99. keyword 100. Mutable 101. Immutable 102. implicit type conversion 103. type casting 104. pass 105. break 106. continue 107. Function 108. _main_ 109, _main_ 110. arguments/actual parameters/actual arguments 110. parameters/formal parameters/formal arguments 112. default parameter 113. default 114. Keyword 115, None 116, _main, 117. Flow of Execution 118. header 119. library 120. module Very Short Answer Questions 1 121. What are tokens in Python ? How many types of tokens are allowed in Python ? Exemplify 122. 123. ‘your answer. [Textbook Q. 1, Chapter 1 (Type Aj] ‘Ans. The smallest individual unit in a program is known as a Token or a lexical unit. Python has following types of tokens : ( Keywords (ii) Identifiers (Names) (ii) Literals (iv) Operators (2) Punctuators What is the difference between a keyword and an identifier 2 ‘Ans. Keyword is a special word that has a special meaning and purpose. Keywords are reserved and are a few. For example, if, elif, else etc, are keywords. Identifier is the user-defined name given to a part of a program viz. variable, object, function etc. Identifiers are not reserved. These are defined by the user but they can have letters, digits and a symbol underscore. They must begin with either a letter or underscore. For ,, chk, chess, trial etc,, are identifiers in Python. What are literals in Python ? How many types of literals are allowed in Python ? ‘Ans. Literals mean constants i., the data items that never change their value during a memnr=- YouTube :Notion Tube Scanned with CamScanner 14 Move FAST WITH COMPUTER SCIENCE (Python) ~ XI fice types of literals : (ii) Numeric literals python allows, I None (i String literals eric (ii) Boolean literals (jv) Special Literal (0) Literal Collections Hoco many types of strings are ‘Ans. Python allows two string tYPes (i) Single line Strings Strings that are terminated in single line (ii) Multiline Strings Strings storing multiple lines of text 1d and processed in Python ? How ? Give examples to [Textbook Q. 4, Chapter 1 (Type A)] like tuples, lists ete. supported in Python ? 124 Can non-graphic characters be nse support your anstoer. ‘Ans, In Python strings, we can include non-graphic characters through escape 125. redefined codes that begin with a backslash(\) following by a Each escape sequence is treated as a single sequences. Escape sequences are PI special character or a group of characters character. Some commonly use \n newline character \" double quotes Is the following statement valid ? Why ? od escape sequences are : \t tab character \" single quote \\. slash character 126. >>> ‘Ans. Yes, the above statement if fully val storing/referring to a string “a”. Is the following statement valid ? Why ? lid in Python where a variable namely @ is 127. >>> “al ‘The above statement may or may not give error. tatement will give no error and Ans If variable a has been defined earlier, the above st produce a result. But if variable a has not been defined earlier, the above statement will give NameErr0r 128. Out of the following, find those identifiers, which cannot be used for naming Variables or Functions in a Python program : [Textbook Q. 5, Chapter 1 (Type A)] price*Qty, class, For, do, 4thcol, totally, Row31, _Amount lowing identifiers cannot be used for naming variables /functions in a Python Ans. Foll program : Price*Qty, class, 4thcol, How are lating constants represented in Python ? Give examples to support ae your answer. 129. [Textbook Q. 6, Chapter 1 (Type A)] Ans, Floating point literals or real literals eal 7 a Is or floats peritan ‘with a decimal point dividing the integer 4 rect real numbers and are rs having fractional parts. ictional parts to represent oz Scanned with CamScanner 139, 140, ML 142. 43. What is the role of comment Move FAST WITH COMPUTER SCIENCE (Python) ~ Xi 1s and indentation in a program ? soplanatory notes tothe readers ofthe program. Compiler or ste but they are useful for specifying additional and logic of the program. ssentable. Its main role is to Ans, Comments provide the comm n regarding the code indentation makes the program more readable and Pre highlight nesting of groups of control statements What is a statement 2 What is the significance of an empty statement ? ion given to the computer to perform any kind of action. tuations where the code requires a statement but empty statement is used. interpreter ignores descriptive informa Ans, A statement is an instructi useful in two requirements simultaneously, An empty statement is logic does not, To fill these statement as an empty statement. are supported by Python ? Name them. [Textbook Q. 14, Chapter 1 (Type A)] Python offers pass How many integer ty “Ans, Python provides following types of integer types : (i Integers (signed), (i) Booleans. What is entry controlled loop ? Which loop is entry controlled loop in Python ? [Textbook Q. 18, Chapter 1 (Type 4)] Ans. The loop which tests a condition before entering into the loop, is called an entry controlled loop. In Python, while is an entry controlled loop. Below are some segments of code, each with a part coloured. Indicate the data type of each coloured part by choosing the correct type of data from the following type- (aint (float (c)bool (a) str (¢) function (f)list of int _(g) list of str [Textbook Q. 20, Chapter 1 (Type A)] (i) L=[ ‘Hiya’, ‘Zoyat, ‘Preet’ ] () if temp < 32: print(L[2]) print ("Freezing") (i) m=) (i) L= [ Hiya’, “Zoya, for 4 in range (3) : n=len w. om Preet . append(i) if Donald in L[1: nl]: print(L) print(M) (o) if n%2e*0: print("Freezing") Ans. (i) Boolean (ii) String (iii) List (iv) Integer () Boolean Find and write the output of the followi lowing pyth : tere He 1 python code : [CBSE Sample Paper 2019-20] eva" while d inx; print(i, end =") ‘Ans, aaaaaa— aoe printing ot ‘eeps printing a's endlessly OR infinite loop Scanned with CamScanner UNIT 1: PROGRAMMING AND COMPUTATIONAL THINKING (Part A} 17 ee EEE 144. What is the internal structure of Python strings ? [Textbook Q. 1, Chapter 2 (Type AD] ‘Ans. Strings in Python are stored as individual characters in contiguous locations, with two-way index for each location. 145, Discuss the utility and significance of Lists, briefly. (Textbook Q. 3, Chapter 2 (Type AY] ‘Ans. A list is a standard data type of Python that can store a sequence of values belonging to any type. ‘Also, lists are mutable types and support item assignment and thus are useful for applications where element changes arc to be stored. 146. What do you understand by mutability ? What does “in place” task mean ? [Textbook Q. 4, Chapter 2 (Type A)} ‘Ans, Mutability means that in the same memory address, new value can be stored as and when needed. ‘The term “in place” means the place of storage for the value remains the same but the stored value changes. 147, What's a (1: 1] if a is a string of at least two characters ? And what if string is shorter ? [Textbook Q. 6, Chapter 2 (Type A)] Ans. It will be an empty string ”. In any case, a[1:1] will return an empty string ? 148. What will be the output of following code if a= “abcde”. >>> af: af4:2) >>> type (al 1:1]) == type (a[1:2]) ‘Ans. The output produced by given code will be : False True 149. What are the two ways to add something to a list ? How are they different ? [Textbook Q. 7, Chapter 2 (Type A)] ‘Ans. The two ways of adding elements to a list are : () append() - adds one item in the end (ii) insert( ) - adds one item at the specified position 150. What are the two ways fo remove something from a list? How are they different ? [Textbook Q. 8, Chapter 2 (Type A)] Ans. The two ways of deleting elements to a list are : (i remove( ) removes one item, its first occurrence, from the list. (ii) pop() - removes one item from the specified position. 151, What is the difference between a list and a tuple ? [Textbook Q. 9, Chapter 2 (Type A)] ‘Ans. Lists are mutable sequence types while tuples are immutable sequence types of Python. 152, Discuss the utility and significance of Tuples, briefly. [Textbook Q. 11, Chapter 2 (Type A)} Ans. Tuples are immutable sequence types of Python and are used in situations where items in a sequence must not change. Scanned with CamScanner 156, 159. 160. YOUTUBE Notion tube— If ais (1, 2, 3) [Textbook Q. 12, Chapter 2 (Type A)] (a) what is the difference (if any) between a * 3 and (a, a, a) ? (0) is a * 3 equivalent toat+a+a2 (c) what is the meaning of a[1:1] ? (d) what's the difference between af1:2] and a[1:1] ? Ans. (a) Expression a * 3 will give a tuple while (a, a, a) will give a nested tuple : (1, 2,3, 1, 2, 3,1, 2, 3) >>> (a, a, a) ((4, 2, 3), (4, 2, 3), (1, 2, 3)) (b) Yes (©) Empty tuple () (d) a [1:2) will give a tuple with one item while a| will give an empty tuple. What is the difference between (30) and (30,) ? [Textbook Q. 13, Chapter 2 (Type A)] Ans. (30) is an integer value while (30,) is a tuple. Why is a dictionary termed as an unordered collection of objects ? [Textbook Q. 14, Chapter 2 (Type A)} Ans. A dictionary is not a sequence type and it accesses its elements with the help of key instead of its index/position. Hence it is an unordered collection of objects. What type of objects can be used as keys in dictionaries ? [Textbook Q. 15, Chapter 2 (Type A)] Ans. Immutable types Though tuples are immutable type, yet they cannot always be used as keys in a dictionary. What is the condition to use tuples as a key in a dictionary ? [Textbook Q. 16, Chapter 2 (Type A)} ‘Ans. Tuples cannot be used as keys of dictionary if these contain any mutable type element such as of list type. Tuples can be used as keys only they contain all elements of immutable types. How is del D and del DI] different from one another if D is a dictionary ? {Textbook Q. 18, Chapter 2 (Type A)] Ans. The statement del D will remove the complete dictionary object, while del Dikey] will remove only one entry from dictionary D. What isthe slice expression that gives every third character of string St, starting with the last character and proceeding backward to the first ? Ans. St[::-3] Consider the following nested list definition and then answer the questions based on this x= [10, [3.141, 20, [30, 'baz', 2.718], ‘foo"} Scanned with CamScanner 7 1 PROGRAMMING AND COMPUTATIONAL THIMONG Pot 4) 19 ‘A schematic for this list is shown below : omc 14 30 ‘dl ‘bat 278 (a) What is the expression that returns the ‘z’ in ‘baz’? (&) What expression returns the list [‘baz’, 2.718] ? Ans. (@) x{1){2}11(2] © xM2I0) 161. What will be the output produced by following code ? >>> gradel = 88 >>> grade? = 99 >>> averagel = (gradel + grade2)/2 >>» average? = gradel + grade2/2 >>> averagel , average2 (a) 85.0, 125.0 (®) (65.0, 125.0) () 85.0, 85.0 (@ (125.0, 85.0) Ans. (B) (85.0, 125.0) 162, What is the output of the following code ? >>>. a= 2**(3*#2) >>> b= (2643) "#2 >>> c= 2083*#2 >>>a, b,c Ans. 512, 64, 512 163, Which of the following is valid arithmetic operator in Python ? li? i)< ia) and [CBSE Sample Pape: Ans.@// 164. Write the type of tokens from the following : (i) if (i) roll_no. ICBSE Sample Paper 2018-201 Ans. (i) Keyword (ii) Identifier 165. What will the following expression evaluate to ? >>> 8/4/2, 8/ (4/2), (8/4)/2 Ans, (1.8, 4.0, 1.0) Scanned with CamScanner 1 Move FAME WII COMPUTER SCIENCE (PyAhon) ~ 2 ——_e Fr What 0 the output of tHe following expression ? print (4 00/(2,0 6 2.6),4.00/2.6+ 2.8, 4.08/2.8/ 2.8]) Von (1,8, 4.0, 1.0) Lo What 0 the output of the following expression ? pe tt (14,00/ (2.04 2.0), 4.00/2.0 + 2.8 ]) Ai [8 4.6) Loo What is the output of the following codes ? (be btm tue (by L=['im', ‘ur') for Lint for fink: Lupper i= d.upper() petnt(i) print(L) Aus (Elm tue) (0) [om tur] Loo What «ill the following code produce ? (oben, tues) () T=("in’, ur’) U1 = range(ten(L)) T1 = range(1en(T)) for Lint for iinT1: UL} t fi] -upper() T{i] = T[i]-upper( ) print(Ly . print (T) Av (a) (OTM, "UR (‘The above code will produce error as Item assignment is not possible in tuples. [Textbook Q. 5, Chapter 2 (Type Bl) 10 Fil the errora, State reasons. Wt, "a", 9.2) & t=[1, "2", 9.2) op=6 tle}=6 (tf, "a", 9.2) (@) t= ‘hello* 1a} oo t[e] =" Any (#) Hem amigninent not possible for tuples as tuples are immutable types. (b) No error, (©) Hirror, Hem being assigned to an invalid index (index out of range). (a) env avnignment not possible for strings as strings are immutable types. VL Name the fiunction/nethad required to : [Textbook Q. 12, Chapter 2 (Type 5)] () chick if string contains only uppercase letters, : (i) ghees the total length of the list. Anws (i) tnupper( ) (hb) beng) Scanned with CamScanner AND CONPUTATONAL THING [Bot 4) ee eee eeaesanw Find the errors in following function definitions : (@) def eain( ) () def Func2() : print ("hello") print (2+3) () def compute( ) = (2) square (a) print (x*x) return asa [Textbook Q 4 Chapter 3 (Checkpoint 31)] Ans. (2) Colon( : ) missing in the function header. (6) If indentation is of four spaces, then No error, else indentation error. (c) If indentation is of four spaces, then No ertor, else indentation error. (a Keyword def missing and no colon ( : ) at the end of function header. 173. Consider a function with following header def info(odject, spacing = 18, collapse = Here are some function calls given below. Find out which of these are correct and which of these are incorrect stating reasons ? For correct function call statements, specify the argument oalues too. a. info( obj) b. info(spacing = 28) €. info( obj2, 12) 4. info( obji1, object = obj12) e. info( obj3, collapse = 0) £. info() g. info(collapse=@, obj3 ) h. info( spacing =15, object = obj4 ) Ans. (@) Correct obj is for positional parameter object ; spacing gets its default value of 10 and collapse gets its default value of 1. (@) Incorrect —_ Required positional argument (object) missing ; required arguments cannot be missed. (©) Correct Required parameter object gets its value as obj? ; spacing gets value 22 and for skipped argument collapse. default value 1 is taken, (@ Incorrect. Same parameter object is given multiple values - one through positional argument and one through Keyword(named) argument, (2) Correct Required parameter abject gets its value as obj3 ; collapse gets value 0 and for skipped argument spacing, default value 10 is taken. () Incorrect Required parameter object's value cannot be skipped. (@) Incorrect. Positional arguments should be before keyword arguments, () Correct Required argument object gets its value through a keyword argument, Scanned with CamScanner MOVE FAST WITH COMPUTER SCIENCE (Python) ~ XI 174. Write the term suitable for following descriptions : [Textbook Q.13, Chapter 3 (Fype Ay (a) A name inside the parentheses of a finction header that can receive a value. (0) An argument passed to a specific parameter using the parameter name, (0 A value passed to a function parameter, (a) A value assigned to a parameter name in the function header. (c) A value assigned to a parameter name in the function call. () A name defined outside all function definitions, (g) A variable created inside a function body. Ans, (@) Parameter (d) Default value () Global Variable 175, Find and write the output of the following python code : a=10 def call(): global a a=15 b=20 print(a) call() () Named argument (©) Argument (&) Named/keyword arguments (g) Local Variable [CBSE Sample Paper 19-20] Ans, 15 176. What do you understand by flow of execution ? [Textbook Q. 3, Chapter 3 (Type AI] ‘Ans. The Flow of Execution refers to the order in which statements are executed during a cludes all the statements that have been executed, from the _main__ program run. I section to statements inside the functions called. 177. What will the following function return ? def addem(x, y, 2): print(x+y+z) ‘Ans. None object will be returned. (no return statement) What will the following function print when called ? [Textbook Q. 4, Chapter 3 (Type B)] def addém(x, ys 2): return x+y +z print(x+y +2) ‘Ans. Nothing will be printed (print( ) statement is unreachable) 179. What is the use of file _init_.py in a package even when it is empty ? [Textbook Q. 5, Chapter 4 (Type A)] 3 (Type BL [Textbook Q. 3, Chapte ‘Ans. In order for a folder containing different modules i.e, py files, to be recognized as a package, a special file namely __init__.py must also be stored in the folder, even if itis empty file. The presence of the file _ i imported using import command). it_.py ina folder, makes it importable package (i.., can be - Scanned with CamScanner OGRAMMING AND COMPUTATIONAL THINKING (Port A) 90, How are following import statements different ? [Textbook @ 7, Chapter 4 (Type Ail (a) import X (&) from X import * (0) from X import a, b, ¢ Ans. (a) It imports all the defined functions and variables of module X and makes available to current program with namespace X. {it imports all the defined functions and variables of module X and makes available to current program within the namespace of current program. (ii) 1k imports only functions/definitions of a, and ¢ of module X and makes available to current program within the namespace of current program. [Name the Python Library modules zhich need tobe imported to invoke the following funcHons (log) (i pow( ) [Textbook Q 11, Chapter 4 (Type A)] Ish Ans. (i) math (fi) math SHORT ANSWER QUESTIONS (oes Non-Programming Questions So ee 182. How many ways are there in Python to represent an integer literal ? ‘Ans, Python allows three types of integer literals : (a) Decimal (base 10) integer literals (®) Octal (base 8) integer literals (©) Hexadecimal (base 16) integer literals (@) Decimal Integer Literals. An integer literal consisting of a sequence of digits is taken to be decimal integer literal unless it begins with 0 (digit zero), For instance, 1234, 41, +97, -17 are decimal integer literals. (b) Octal Integer Literals. A sequence of digits starting with 0 (digit zero) is taken to be an octal integer. For instance, decimal integer 8 will be written as 010 as octal integer. (8p = 103) and decimal integer 12 will be written as 014 as octal integer (129 =14y) (0) Hexadecimal Integer Literals. A sequence of digits preceded by 0x or OX is taken to be an hexadecimal integer. For instance, decimal 12 will be written as 0XC as hexadecimal integer. Thus number 12 will be written either as 12 (as decimal), or as 014 (as octal) or as OXC ' (as hexadecimal). 183. The following code és not giving desired output. We want to input valve as 20 ard obtain output as 40. Could you pinpoint the problem 2 Number = input( "Enter Number" ) DoubleTheNumber = Number * 2 Print (DoubleTheNumber ) ne ee Scanned with CamScanner 24 Ty COMRUT cE ( Ans, The problem is that input( ) returns value as a string, so the input value 20 is returned as string ‘20' and not as integer 20. So the value of variable DoubleTheNumbers is 2020 in place of required output 40, Also Print is not legal statement of Python ; it should be print. Is. Why is following code giving errors ? name = "Rehman" print ("Greetings 111") print("Hello", name) print ("How do you do ?") Ans. The problem with above code is inconsistent indentation. In Python, we cannot indent a statement unless it is inside a suite and we can indent ‘only as much as required. Thus, corrected code will be : | name = "Rehman print("Greetings 111") print("Hello", name) | print ("How do you do 2") 185. What are data types ? What are Python's built-in core data types ? Ans. The real life data is of many types. So to represent various types of real-life data, programming languages provide ways and facilities to handle these, which are known as data types. Python’s built-in core data types belong to : = Numbers (integer, floating-point, complex numbers, Booleans) > String > List > Tuple > Dictionary 186. If you are asked to label the Python loops as determinable or non-determinable, which label would you give to which loop ? Justify your answer. Ans. The ‘for loop’ can be labelled as determinable loop as number of its iterations can be determined beforehand as the size of the sequence, itis operating upon. The ‘while loop’ can be labelled as non-determinable loop, as its number of iterations cannot be determined beforehand. Its iterations depend upon the result of a test-condition, which cannot be determined beforehand, 187. There are two types of else clauses in Python. What are these two types of else clauses ? Ans, The two types of Python else clauses are : (0) else in an if statement () else in a loop statement The else clause of an if statement is executed when the condition of the if statement results into false. {The else clause ofa loop is executed when the loop is terminating normally i., when its War condition has gone false for a while oop or when the for loop has executed for the last value in sequences, ~ Scanned with CamScanner UNIT 1: PROGRAMMING AND COMPUTATIONAL THINKING (Por a) 25 I OS NRING AND CONPUATONN TANKS er 1s, What are immutable and mutable types? List inmmutable and mutable types of Python, {Textbook Q. 15, Chapter 1 (Type A] ns. The immutable types are those that can never change their value in place. In python, the following types are immutable : integers, floating point numbers, Booleans, strings, tuples. “The mutable types are those whose values can be changed in place. Only three types are mutable in Python, which are ists, dictionaries and sets. 169, What is the diffrence bettcen implict type conversion aud explicit type conversion ? [Textbook Q. 16, Chapter 1 (Type A)] ‘Ans. An implicit type conversion is a conversion of data type of a value, performed by the compiler without programmer's intervention. This takes place when an expression contains values of two different data types in it, The explicit type conversion of an operand to a specific type is called type casting. The explicit type conversion is forced by programmer using the typecast operator ( ). For example, # implicit conversion will take place here as A and B are of different types D=A+(int)B — # explicit type conversion of B has taken place here 190. An immutable data type is one that cannot change after being created. Give three reasons to use immutable data, {Textbook Q. 17, Chapter 1 (Type AI] Ans. The immutable types offer following advantages/benefits : () Values remain safe as values cannot be changed in place. (i) Immutable types are more suited for things where values must remain intact, such as keys of a dictionary. (i) Immutable types internally give a better (optimised) performance as value change overheads are not there. 191. Explain the use of the pass statement. Ilustrate it with an example. [Textbook Q. 19, Chapter 1 (Type A)] Ans. In Python, the pass statement is an empty statement as it does nothing. Wherever Python encounters a pass statement, Python does nothing and moves to next statement in. the flow of control. For example, in the following loop, for every value divisible by 2, Python will do nothing because of pass statement. For other values, it will print the value of variable val. Af val 82 ==0: pass. | for val in range(3, 9) : | print (val) | | Scanned with CamScanner 26 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ Xi In th siown code fragments, indicate the data type of each coloured part by choosing the 192. In the below given eode fragme correct type of data from the following type (aint (b) float (c)bool (d) str (e) function (f) list of int (g) list of str [Textbook Q. 20, Chapter 1 (Type A)] () L=input2ine.split( ) Ky while L !=(): it converts the ead print(L) line into words belts] (ii) L= [ ‘Hiya’, ‘Zoya’, ‘Preet’ ] print(L[0] + [2] ) Ans. (i) List (ii) String 193. Fill in the missing lines of code in the following code. The code reads in a limit amount und « list of prices and prints the largest price that is less than the limil. You cun assume tat all prices and the limit are positive munbers. When a price 0 is entered the program terminate and prints the largest price that is less than the limit, (Textbook Q. 1, Chapter 1 (Type B)} #Read the Limit Limit = float (input("Enter the limit") max_price =@ #Read the next price next_price = float(input ("Enter a price or @ to stop:")) while next_price >@: #Read the next price if max_price > 0: else: Ans. ‘#Read the Limit Limit = float(input (“Enter the limit")) max_price=@ #Read the next price next_price = float (input(" while next_price >@: Enter a price or @ to stop:")) Af next_price < limit and next_price > max_price : max_price = next_price #Read the next price next_price = float, if max_price > Print("Largest else: (Gnput (“Enter a price or @ to stop:")) price less than the limit is", max price) Print(“No price less than the Limit was entered ) Scanned with CamScanner N11 PROGRAMMING AND COVPUTATONAL THINKING [Port 4) dict the outputs of th count = while count < 18: print (Hello}) count += 1 @ x=10 y= while x>y: print(x, y) @) Oo (0) keepgoing = True x= 100 while keepgoing: print(x) X=x-10 if x< 50: keepgoing = False ® oO () x=45 while x < 5@: print(x) © (m) for x in [1,2,3,4,5]: print(x) for p in range(1,1@): print(p) on) (g) for z inrange(-500,500,168): print(z) (hy) x=10 y=5 for i in range(x - y*2): print(%", i) Ans. (@) It prints “Hello” 10 times in separate lines () 100 91 82 73 64 (2) ae Textbook Q. 2, Chapter 1 (Type B)l for x in range(19): for y in range(S: tea print(c) =(2,2,3] counter =@ while counter < Len(x): print(x[counter] *%) fory inx: print(y*"* *) counter +=1 for x in"lamp: print(str.upper(x)) x="one’ y= "two counter = 8 while counter < len(x): print(x[counter], y[counter]) counter +21 x= "apple, pear, peach” y=x.split(", ") forziny: print(z) x="epple,pear, peach, grapefruit’ y=x.split(, ") for ziny: if zc: print(str.lower(z)) else: print(str.upper(z)) [Note : No space ater comma} 100 80 70 60 50 Scanned with CamScanner 28 AVE FAST ATE COMIAITER SOTENGE (PytOnD = NIL GTi ad BNDE ESS loopy that M & oops printing i @ oa waa : te ‘ ‘ 4 aa I aaa WA oo. 4 : ae 3 wae 4 s (Ay). 6 A v “ 8 P 9 Woot (S00 Ar ~400 eo ~300 ~200 (1m) apple ~100 pear 0 peach 100 200 (1) appte 300 PEAR 400 PEACH (1) No output (this code prints nothing) orapefruit () so 195, Rewrite the following ende in python after removing all syntax error(s) Colour anid Underline each correction done in the code: [CBSE Sample Paper 2019-20} 30+ To for K An range(o,To) TF KX «= 0; print (K* 4) Else: print (K+ 3) Ans. Jo=30 4 vardable name should be on LHS for K inrange(O,To) : Was missing LEKMA wm OF W itshouldbeinlowercase print (K #4) Welse should be in Lowe print (K+ 3) mente awe _ i ~ Scanned with CamScanner UNIT 1: PROGRAMMING AND COMPUTATIONAL THINKING (Port A) 29 A196. Find and trite the output of the following python code : (TB Q. 8, Chapter (Type BH ~ for Name in ["Jayes’, "Ramya", ‘Taruna’, "Suraj"] : print (Name) Af Name[ 0] = break else: print (‘Finished! ") print (‘Got it!") Ans. dayes Finished! Ramya Finished! Taruna Got it! 197. Find the errors in following code and write the correct code. (i) Underline the corrections (i) Write the reasonlerror next to it in comment form. Pint "ABC \) @ ifyssiv ro in range(v): else: print! (ov2") (0) Def s(x): a= ‘k? print(a * x) print(a* str(x) ) for in [1, 2’, 10: s(n) () FoRxin[2, 5, 8] ' nentx print(n) (@)— x=True y=False z= false ifx,yjzt print "yes else: print "no" Fe Scanned with CamScanner 30 MOVE FAST WIN COMPUTER SCIENCE (thon) I (Le [rat my tet, any ve6 for { in Len(1): Mi }aey veved print(ye "yyy "Le", 1) de trar, te ve ‘6 for in: Ii} ty Veve2 print("ve",v, "Le", 1) ‘dy @) L=[rar, eo, t= (0,1, 2,3) vi=6 V2 = «6 forint: ALi] v2 vievi-a print(t * t) print(t ( vi} ) print(t (v2: ] 0] () s= faa, 13, 15) 0 for nin arange(len(s)): tot = tot + s(n) print(tot) ) def extract_lesser (1, v): for num inl: if less_listappend(num) Return less_list (k) forfizzburz inrange(1, 15, ): Af fazzbuzz 83 = 0 and Fizy print "fizzbuzz" Continue else if Fizzbuzz 3 un continue else fizzbuzz aS 220; Print(*buzz") Print(Fizzbuzz) oe buzz & 5 ang: S* 41, 23, 25) for nin en(s) : tot = tot + stn) print(tot) Scanned with CamScanner | fl PROGRAMING AND CONPUATONAL HKG até) 31 Ans. (a) a 4 v must be defined before being used ifves: for j in range(v): print("ABC") # () missing for print() else: © wrong indentation; else clause can either be for if OO # or for for loop print ("xv2") # () missing for print() w def s(x): 4 def should be in lowercase ast’ print (atx) print(a+str(x)) # two strings cannot be used with * operator, s but can use + operator forn in (1, 2,10}: # (4) loop variable not defined 4 (4) closing ] missing s(n) # incorrect indentation (od neo #t variable n must be defined before use j for x in [2, 5, 8]_: # for should be in lowercase and : missing at the end of for | nen+x print(n) @ rue y=False # either false must be a predefined variable or #use Boolean value False ifxor y and z: # Boolean values / expressions must be combined using # or/and/not operators to form a condition print ("yes") #() missing for print() else: print ("no") #() missing for print() C) Le[lat, bY, te", a] v=6 for i in range(len(1)): #Len(1) will return an integer not an iterators : #range(1en(1)) will return an iterator #1[1] contains a string and an int can’t be # added toa string 14] veve1 print("v=",v, "l=", 1) Scanned with CamScanner MOVE FAST WITH COMPUTER SCIENCE (Python) - xi for} inrange( len (1) ) : #() loop variable missing { i) Loop vardable i is used as index of list Lin & the loop so i must get integer values fron : # iterator, thus range ( Len(L) ) given here lti]+ev veve2d cd Cannot be used with string and integer, but * print("v=", v, " Can be seg ", 1) vas ‘6 forint : Ili) 42.2 vlsvil-1 print( t+t) a tuple cannot be multiplied with a tuple, Print(t [ivi] ) #v1 is6, index out of range, howeverwith slice it wil work print(t [int(v2):]) #a tuple slice can contain only integers #3 missing ) s=[11, 13, 15] tot =@ for n in range(1en(s)): # tot must be defined before being used # built-in function is range() not arange() tot = tot + stn] #incorrect indentation and #sisa list; toaccess its elements # square brackets are used print(tot) @ s= (11, 13, 15] tot =@ for nin range(len(s)) : # tot must be defined before being used # 1en(s) returns integer which is not iterable, # tomake an iterable from integer range() is used incorrect indentation tot = tot + s[n} print(tot) “ def extract_Lesser (1, v): less_list = [] for num ind a List must be defined before being appended ifnum once for outerloop’s value 0 (range (0, 2, 2) will give (0] > thrice for outerloop’s value 4 (range (0, 6, 2) will give [0, 2, 4] 199, Is the loop in the code below infinite 2 How do you know (for sure) before you rum it? m=3 nes Scanned with CamScanner a MOVE FAST Wil] COMPUTER SCIENCE (Python) — xl 7 “a whiten 10; ment nedtnom prfat(n, m) Textbook Q. 5, Chapter 1 (Type gy ‘Ans. No, the fp in no! infinite BECAUSE the loop control variable's value is getting updated inside the loop body witha value that will make it reach the condition sometime. The output produced willbe; 6 4 75 86 97 108 200, What is indeving in context to Python strings 7 Why is it also called two-way indexing 2 Ans, In Python strings, each individual character is given a location number, called indey and this process is called indexing. Python allocates indices in two directions : > in torward direction, the indexes are numbered as 0, 1, 2,.... length-1. > in backward direction, the indexes are numbered as -1, ~2, ~3....ength. This is known as two-way indexing, 201, What is a string slice ? How is it useful ? ' Ans, A sub-part or a slice of a string, say s, can be obtained using s [n : m] where and : my ave integers. Python returns all the characters at indices m, 1 +1, n+2...m-1 eg., ‘Welldone' [1:4] willgive ‘ell’ 202, Write a Python script that traverses through an input string and prints its characters in different lines ~ tivo characters per line, [Textbook Q. 2, Chapter 2 (Type A)] Ans. name = "string" size» len(name) for 4 in range(, size, 2) : print(name(1], name[1+1]) 203. Following code is not producing any output and seems to have gone in endless loop Ast = ['ab", ‘'cd"] for 1 4n Ist: Ast append(4 .upper()) print (1st) (a) What could be the reason ? (h) Could you suggest a solution for above code problem 2 Ans, (a) Initially the list x contains 2 elements and with every pass of the loop, an element 1s axlded to fst and the loop has to repeat till the last element of the list. Since list keeps asing, In size in each loop iteration, the loop will never end, hence the endless loop. ns by clearly specifying the last element for loop "8, one possible solution could be : 8 oniner (0) If we can limit the loop iterat iteration, the loop will end after that, Ist = ['ab', 'ed"] for 1 in Ist[ :2): Ist. append(1.upper()) print (1st) Scanned with CamScanner UNT 1: PROGRAMMING AND COMPUIATONAL THNKNG (Port A) 35 204. What is the output of the following ? L=['in', ‘ur') for i ink: print(i.upper()) print(L) = » YouTube :Notion Tube Cin’, ‘ur'] 205, What is the output of the following ? iso while True: if (i+ 34 break print(i, end its1 | Ans. 910 206. What is the output of the following ? isa while True: if ix 007 break print(i, end=*") ite1 Ans. 456 (Note. 007 is a valid integer, written in octal forming) 207. What i$ the output of the following ? isa while True: if i% @08 == @: break print(i, end = ite1 ‘Ans. The above code will give Error because 0o8 is not a valid integer. Any number beginning with 0 is treated as octal number and octal numbers cannot have digits § and 9. Hence 0o8 is an invalid integer. 208. What is the output of the following ? True = False while True: print(True) break ‘Ans, The above code will give Error because keyword True has been used as variable {in first line of code True = False). We cannot use keywords as variables or any other identifiers. 4 Scanned with CamScanner 5 rer SCIENCE (Python) — 36 ! aro output of the flores ? . 209), Wit is me a peaks for i inx? . bape (i, end="") print(i-upper()> end = print(i, end = i-upper() Ans. (abcd ( aged ‘p10. What isthe output of te following’? (a) x= ‘abed" ® x= abed ; for i in range(len(x)) + for i in range(1en (x) 5 print(i, end="") print (x[iJ, end" ') () abcd ‘Ans. (a) 0123 ‘ite What isthe output of the following ? x=12 for iinx: print(i) and is used in place of a is an integer eger values cannot be used as [7B Q. 1, Chap. 2 (Type BI] will produce error as x iterables. ‘Ans. The above code hence the error int ' sequence or iterable in a for loop; ! 212 Wat wil be the onfput produced by following code fragments ? tr(123) () x="hello"+\ @ hello" * 3 “to Python" +\ print(x, y) “world” x="hello” + "world" for char inx : y=len(x) y=char print(y, x) print(y, end="") (_ x="helloworid” print(x{:2], xf:-2], x[-2:]) print(x(6], x{2:4]) print(x[2:-3], x[-4:-2]) Ans. (a) heTloheTIohe110 123 10 heTloworld (Do hrerdedes (0 he hello wor 1d whl To wo or 213. Write a short Python code se egment that add prints the average (mean) length. | Nie oF ite rt st anal the ‘extbook Q. 2, Chapter 2 (Type B)] ‘Ans. Line = "This is going to be fun" Lst = Line. split() total =0 S————_ Scanned with CamScanner UNIT L:PROGRAMMING AND COMPUTATIONAL THINKING (Port A 87 avg = total/count print("Original line :", Line) print("List of words :", Lst) print("Total length of all words :", total) print (“Average length of all words :", ave) 214. Predict the output of the following code snippets ? [Textbook Q. 3, Chapter 2 (Type BY] a= (1,2,3,4,5) print(a(3:0:-1)) Ans. (4, 3, 2] 215. Predict the output of the following code snippets? [Textbook Q. 4, Chapter 2 (Type B)] (a) arr=[1, 2, 3, 4,5, 6] (0) Numbers =[9, 18, 27, 36] for i in range(1, 6): for Num in Numbers : arr(i- 1] =arr[i] for Nin range(1, Num&s @ for i in range(®, 6): print(N, "#", en print(arr[i], end="") print() Ans. (@ 234566 (b) L#le2e1#e2e3e% 216. Find the errors. State reasons. [Textbook Q. 5(e), Chapter 2 (Type B)] for Name in [Amar, Shveta, Parag] IF Name[@" St: print (Name) Ans, Errors : (The for loop is not created as suite : missing at the end of for loop) (i) Values Amar, Shveta, Parag are not enclosed in quotes; also there are no variables defined with these names ; hence they cause error. (iii) IF is not a valid statement in Python. It should be if. 217. Assuming words is,a valid list of avords, the progean below tries to print thelist in reverse Does it ave an error ? If so, thy ? (Hint. (There. are roo, problents with the,code:) for i in range(len(words), @, -1): print(words[i], end =" ') [Textbook Q. 6, Chapter 2 (Type B)) Ans. (The statement for i in range(len(words), 0, -1) will give error because, words[i] will access the first value as words[len(words)] and it is not a valid syntax for the list words. Valid indexes are from 0 to len(words) -1 a —— —— Scanned with CamScanner Yy (4) Awe correct the above line of code as for i in range len(wotds) ~1 , 0, -1), stil, Will not print the first word as ending index given in expression tange(len(words) - 1, 0, ~ 1) and ending index is not included in the range( ) result The corrected statement should be for i in range(len(words) -1, ~1, -1) : a8 Mow FAST Wilt! COMPUTER SCIENCE (Python) = xt 21K. What would be the output of following code if ntpl = (“Hello”, “Nita”, "How's", “life 2°) 2 (a, b,c, d) =ntpl print("a dss", a) print(" is:", b) print("e iss", c) print('d s:", d) ntpls (a, b,c, d) print (ntp1[0][0]4ntp2[1][2], ntp1[1]) Ans, ais: Helo bis: wita cis: How's dis: life? ii Nita 219. What will be the output of the following code snippet ? (Textbook Q. 10, Chapter 2 (Type BY] my_dict = {} my _dict((1,2,4)] =8 my_dict[(4,2,1)] =10 my _dict[(1,2)] =12 sum = @ fork inmy dict: sum += my_dict[k] print (sum) print(my_dict) Ans. 30 {C, 2, 4): 8, (4, 2, 1): 10, G2, 2): 12} Write a method in python to display the elements of list thrice if it is a number and display the clement terminated with “# if it is not a number. (Textbook Q. 11, Chapter 2 (Type B)] [Textbook Q. 7, Chapter 2 (Type B)] 220. For example, if the content of list is as follows List = ['41', "DROND', “GIRIRA’, '13", ‘ZARA'] The output should be 414442 DRONDH GIRIRAIH 131313 ZARA Ans. List ['41', 'DROND', “GIRTRAI", "13°, *ZARA‘] forw in List: ifw.dsdigit(): print (w*3) else: print (w+"#") - Scanned with CamScanner 221 223. Trace the following code and predict output produced by What is the significance of Ans. Creating functions in programs WAL PROGRAWIMING AND COMPUTATIONAL THNENG (207 4) 39 tions in a program ? s very useful. It offers following advantages : (i) The program is easier to understand. Main block of program becomes compact as the code of functions is not part of it, thus is easier to read and understand. (i) Redundant code is at one place, so making changes is easier. Instead of writing code again when we need to use it more than once, we can write the code in the form of a function and call it more than once. If we later need to change the code, we change it in one place only. Thus it saves our time also. (iii) Reusable functions can be put in a library in modules. We can store the reusable functions in the form of modules. These modules can be imported and used when needed in other programs. From the program code given below, identify the parts mentioned below : 1 def processNumber(x): 2. x=72 3. return x+3 4 5. ya5a 6. res = processNunber(y) Identify these parts : function header, function call, arguments, parameters, function body, main program Ans, Function header: def processNumber(x) : in line 1 Function call: processNumber(y) in line 6 Arguments : y in line 6 Parameters : x inline 1 Function body in ines 2 and 3 Main program: in lines 5 and 6 res = processNumber(y) 1. def power(b, p) : 2 y=b**p 3. returny 4 5. def caleSquare(x) : 6. a= power(x, 2) 7 returna 8. 9. neS 10. result = calcSquare(n) + power(3, 3) 11. print(result) Scanned with CamScanner | 40 MOVE FAST WITH COMPUTER SCIENCE (Python) — Xl _____] ‘Ans. Flow of execution for above code will be = 135393109536 3132337677710 1 723351054 ‘The output produced by above code will be : 52 224. Trace the flow of execution for following programs : (a) 1 def power(b, p): (b) 1. def increment (x) : 2 r=b**p 2. xex41 3 returnr 3. 4 4, #main program 5 def cpower(a): 5. x=3 6 arar2 6. print(x) 7 a= power(a, 0.5) 7. increment (x) 8 return a 8. print (x) 9 18 n=5 11 result = cpower(n) 12 print (result) (c) 1. def increment(x): 2 z=45 3. x=xel 4. return x 5. . « »in¥OUTUDe :Not Tub s mm YOUTLUDE -NOTION IUDE 8. print(y) 9. y= 4increment(y) 10. print(y) 11. q=77 12. print(q) 13. increment(q) 14. print(q) 15. print(x) 16. print(z) nt eee Ans. being retumed by increment( ) (6) 1559697313258 © 197 228999192-93-9459-510411 9125134 13233545 225. Find and write the output of the following python code ? 4 [cbse aStrte Peper 2019-20} jotmeme teeeae fef Change(P, Q= 30): not being stored aryuhere. . P=P4Q Q=P-9 - Scanned with CamScanner UNIE 1 PROGRAMMING AND COMPUTATIONAL HAINKING (Part A) al print(p,"#",Q) return (P) Re 150 S= 100 R= Change(R,S) print(R,"#",S) $= Change(S) Ans. 150 # 50 150 # 100 300 # 70 236, A program: having multiple functions is considered better designed than a program without any functions, Why ? [Textbook Q. 1, Chapter 3 (Type AIL Ans, Program having functions is considered better, because : (i I makes program handling easier as only a small part of the program is dealt with at a time, thereby avoiding ambiguity. (ii) Tt reduces program size. (iii) We makes a program more readable and understandable to a programmer thereby making program management much easier. 227. What all information does a function header give you about the function ? [Textbook Q. 2, Chapter 3 (Type A)! Ans. A function header tells about : ( the name of the function, (ji) the number of arguments or parameters. 228, What is the difference between the formal parameters and actual parameters? What are their alternative names? Also, give a suitable Python code to illustrate both, Ans, Actual Parameter is a parameter, which is used in a function call statement to send the value from calling function to the called function. It is also known as Argument. Formal Parameter is a parameter, which is used in a furiction header of the called function to receive the value from actual parameter. It is also known as Parameter, For example, def addEm(x, y, 2): print(x+y+z) addem(6, 16, 26) In the above code, actual parameters are 6, 16 and 26 ; and formal parameters are x, y and z 229, What is the utility of : (i) default arguments, (ii) Keyword arguments ? [Textbook Q. 5, Chapter 3 (Type A)] with a default value set to them. This ed value WHEN no value is provided Ans. (i) The default parameters are parame default value is automatically considered as the ps for that parameter in the function call statement. Thus default arguments are useful when we want to skip an argument in a function call statement and use the default value for it instead, Scanned with CamScanner 42 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ Xi (ii) The keyword arguments give complete control and flexibility over the values sent as arguments for the corresponding, parameters. Irrespective of the placement and order of arguments, keyword arguments are correctly matched. 230. Differentiate between fruitful functions and non-fruitful functions. [Textbook Q. 8, Chapter 3 (Type A)] Ans, The functions that return a value ie, non-void functions are also known as fruitful functions. The functions that do not return a value, i, void functions are also known as non-fruitful functions. 231. Can a function return multiple values ? How ? [Textbook Q. 9, Chapter 3 (Type A)] Ans. Yes, a Python function can return more than one value. To return multiple values from a function, the return statement should have a comma separated multiple values, e.g,, following return statement is returning three values : return 23, (a+b), 3*#5 252. What do you understand by local and global scope of variables ? How can you access a global variable inside the function, if function has a variable with same name. {CBSE SP 19-20} Ans. A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition. A variable declared outside of all the functions or in global scope is known as global ble. A global variable can be accessed inside or outside of the function where as local variable can be used only inside of the function. Ifa function has a local variable name asa slobal variable, then in that function scope, the local variable will hide the global variable with the same name. We can access a global variable having the same name as a local variable by declaring its name with keyword global, e.g., as global A. 233. What is the difference between a local variable and a global variable ? Also, sive a suitable Python code to illustrate both, [Textbook Q. 11, Chapter 3 (Type A)] Ans. The differences between a local variable and global variable are as given below: een Keraeie Global Variable 1. JI is a variable which is declared within a] It is a variable which is declared outside all function or within a block the functions 2, | It is accessible only within a function/block in | It is accessible throughout 7 which itis declared ck in | It is accessible throughout the program. For example, in the following code, x, xCubed are global variables and n and on are local variables. def cube(n} cn=ntnén return cn x=10 xCubed = cube(x) Print(x,"cubed is", xcubed) Scanned with CamScanner UNIT 1: PROGRAMMING AND COMPUTATIONAL THINKING (Part A} 43 ar RIS AND CONTATIONS. TERKING (Port A) 234. (@) What will the following codes print ? ( def addem(x, y, 2): (i) def addem(x, y, 2): print(x+y+2z) Kextytz def prod (x, y, 2): def prod (x, y, 2) return x*y "2 return x *y* 2 a= addém(6, 16, 26) a= addem(6, 16, 26) b=prod (2, 3, 6) b= prod (2, 3, 6) print(a, b) print(a, b) (b) In the part (a)’s code, identify the void and non-void functions. The previous code stores the return values of both void and non-void functions in variables. Why did Python not report an error when void functions do not return a value ? Ans. (a) (i) 48 (i) None 36 None 36 (®) Void function 2 addem( ) Non-void function : —_prod( ) In Python, void functions do not return a value; rather they report the absence of returning value by returning None, which is legal empty value in Python. Thus, variable a stores None and it is not any error. 235. Consider below given function headers. Identify which of these will cause error and why ? () def func(a=1, b): (i) def func(a=1, b, (ii) def func(a=1, b= : (iv) def func(a=1, b=1, ¢=2, 4): Ans. Function headers (i), (ii) and (iv) will cause error because non-default arguments cannot follow default arguments. Only function header (iif) will not cause any error. 236. What are the errors in following codes ? Correct the code and predict output : (@) total =0; (8) def Tot(Number) #ethod to find Total def sum( argi, arg2 ): Sum = @ total = argl + arg2; for C in Range (1, Number +1) : print(“Total :", total) Sum +=C return total; RETURN Sum sum( 18, 20); print (Tot[3]) #Function Calls print("Total :", total) print (Tot [6]) [Textbook Q. 1, Chapter 3 (Type B)! Ans. (a) = Wrong indentation for return statement > Semicolons should be avoided (3 statements have it) > Range( ) is not a valid function; it should be range( ) > RETURN is not a valid statement. It should be return. > Function calls use parenthesis, ie, () (not square brackets[ ] ) to pass values. Thus Function calls for Tot( ) would be a Tot(3) and Tot(6) ® Scanned with CamScanner 44 MOVE FAST WITH COMPUTER SCIENCE (Python) - Xi 237. Consider the following code and write the flow of given for your reference. Beevanesune Ans. def power(b, Pp): ysb**p return y def calcSquare(x): a=power(x, 2) returna nes result = calcSquare(n) print(result) 13539310 954691323376 97>10911 238. Determine the output of the following : @ © © def power(a, b= 2): n=l for i in range(b): repta returnr print ( power(4) ) print ( power(4, 3) ) def func(text, num): while num > @: um = nun = 2 print(num) num = 4 func( ‘Hello’, num) print (num) def calc(numbers) ; res=@ for x in numbers: res +=x return res print(sum((8, 2, 3, @, 7))) (&) def func( alist ): + alist = [1,2,3.4] print (alist) return nylist = [10, 20,30] func( mylist ) print (mylist) (@) def printit(1ista): m=n=list1[0] for ain list1: ifacn: nea ifa>m: ma print( "Biggest", m, “Smallest”, n) List1 = [2, 13, 11, 15, 6] printit(list1) () def myfunction(str1): rstris'* index = len(str1) while index > @: if stra[ index - 1 ].isalpha(): rstri += stri[ index - 1] index = index - 1 returnrstri print (myfunction( '1234abcd")) Scanned with CamScanner execution for this. Line numbers have been [Textbook Q. 2, Chapter 3 (Type By) — LUNIE 1 PROGRAMMING AND COMPUTATIONAL THINKING (Part A) 45 UNIT PROGRAMMING AND COMPUTATIONAL THINKING (Part A) (g) def determine(s): d= ("UPPER” for ¢ins: if c. isupper(): L["UPPER"] +22 elif c.islower(): d["LOWER"] +21 else: pass print (“Original String : ", s) print ("Upper case count : ", d[“UPPER"]) print (“Lower case count: ", d["LOWER"]) determine( ‘These are HAPPY Times?) ©, "LOWER" : 0) (i) def unique(1): xe[] for ain: if anot inx: x. append(a) return x print(unique({’a',"b',"r*,"a',*¢','a","d",‘a","b',*r",'a"])) () def compute(s): x=(] for i in range( len(s)): a=s[i] b=a.upper() if anot inx and b not inx : ifa>'p': x.append(a.upper()) else: x. append(a) return x print (compute( ‘abracadabra')) @ def create(s): enum =" 1 = range ( len(s)- 1) for nin: if s(n] == s{n44]: enum += s[n].upper() else: enum += s[n] return enun print(create(“Excellencee") ) Scanned with CamScanner 40 M ay defeat enum = fn in range 2en) ) ifn 2== 0 enum += 2[7] elif n% 3272 enum += 1[0] upper() return enum int tg? eo uct tat, td's a int, 'a'D) prant(evn( atytbt, ne se Be Ans. i o © @ a 1, 234) 3 piggest 15 smallest 2 oa (10, 20, 30] 2 1 0 4 © ” @) ; ; 20 deba original string : These are HAPPY Times i upper case count : 7 1 Lower case count: 11 (hi) @ tat, tht, ety tet 18D pat, tb, tRt, fet ‘dD 0 © Excel. 1encE aracdbRa 230, What will be the output of following programs 2 (i) numed (i) num=4. def myfunc(): def myfunc(): ‘ ree num num = 18 print (num S return num print (myfunc()) print (num) print(num) print (myfunc()) (iii) nume print (num) dof myfunc(): global num (iv) def display(): num = 10 __ brint(“Hello", end= * *) return num display() print (num) print("there!") print (myfunc()) print (num) Ans. [Textbook 4 nmeamatmea ted ~ _ iin ills. Scanned with CamScanner 20 10 (iv) Hello therel 240, Find and write the output of the following python code ICBSE Sample Paper 19-20] def fun(s): k= len(s) m." for i in range(@,k): Af(s{4] -Asupper( )): m=mes[i].lower( ) elif s[i].isalpha( ): m=ms[i) .upper( ) else: mem+'bb* print(m) fun( 'school2@com' ) Ans. SCHOOLbbbbcom 241. Which names are local and which are global in the following code fragment? invaders = "Big names" pos = 200 level = 1 def play() : max_level = level +10 print (Jen (invaders ) == @) return max_level res = play() print(res) Ans. Global names: _ invaders, pos, level, res Local names =: ~—max_level 242. Write a function that takes a positive integer and returns the one’s position digit ofthe integer. Ans, def getOnes (num) : # retunn the ones digit of the integer nun onesDigit = num %10 return onesDigit Scanned with CamScanner 48 MOVE FAST WMH COMPUTER SCIENCE (non) ~ 243. What is wrong rwith the following function definition ? [Textbook Q. 7, Chapter 3 (Type ny def addém(x, y, 2): return x+y +z print(“the answer 1s", x+y +z) ‘Ans. The statement with print( ) is unreachable in above code as it follows the retury statement. As soon as the return statement gets executed, the control returns from the function and no other statement gets executed. 244. Consider the code below and answer the questions that follow : def multiply(number1, number2): answer = nunber1 * number2 return(answer) print (number, 'times*, number2, output = multiply(5,5) answer ) (i) When the code above is executed, what gets printed ? (ii) What is variable output equal to after the code is executed ? [Textbook Q. 10, Chapter 3 (Type B)] Ans. (i) Nothing gets printed (as print() is after the return statement) (i) 25 245. Find the errors in code given below : [Textbook Q. 11, Chapter 3 (Type B)] (@) def minus(total, decrement) output = total - decrement print (output) return (output) (&) define check() N= 4dnput (‘Enter N: ') is3 answer =1+49*4/N Return answer (Q) def alpha (n, string = ‘xyz", k= 10) : return beta(string) returnn def beta (string) return string == str(n) print(alpha(*Valentine’s Day"):) print(beta (string = 'true')) print(alpha(n=5, "Good-bye") :) Ans, (a) Syntax error. Colon (:) missing in the end of function header, Scanned with CamScanner nT 1. PROGRAMMING AND COMPUTATIONAL THINKING (Pott A) 49 ord to define a function is def ( not define). (b) Syntax error. K ‘Also, colon ( : ) missing in the end of function header. Return is not a valid statement. It should be return. (0 No error in function alpha’s definition. (Multiple return statements are syntactically legal. But in above code, the second return statement is unreachable). In function beta( )'s definition, Colon (:) missing in the end of function header. In _main__ part, the colons at the end of first and third print( ) statements is invalid (not enclosed in quotes) In third print( ) statement, in the function call of alpha( ), positional argument follows keyword argument, which is a syntax error. 246. In the following code def funci( ): asi be2 def func2( ): c=3 d=4 ich variables are in the same scope ? [TB Q. 14, Chapter 3 (Type B)I e=5 Ans. Variables a and b, have same scope — function scope of funcl( ) Variables ¢ and d, have same scope - function scope of func2( ) 247. What is the output of following code fragments ? [Textbook Q. 17, Chapter 3 (Type B)] () def increment(n): n.append([4]) return n L=[1, 2,3) M= increment (L) print(L, M) (i) def increment(n): n.append([49]) return n(@], {1}, n[2], n[3] L= (23, 35, 47] mL, m2, m3, m4 = increment(L) print(L) print(mi, m2, m3, m4) print(L[3] ==m4) Ans. @ (1,2, 3, (47), 2,3, (41) (i) (23, 35, 47, [491] 2335.47 [49] True Scanned with CamScanner xi 50 MOVE FAST WITH COMPUTER SCIENCE (Python) 248. What is a module, package and a library ? Ans. Module. A module is a file with some Python code and is saved with a py extension. Package. A package is a directory that contains along with some special files such as _ init__.py. Library. A Python library is a reusable chunk of code that is used in programy script using import command. A package is a library if it is installable or gels attached to sife-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. 249. What is a Python module ? What is its 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 easily be used subpackages and modules in j 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. 250. What are docstrings ? How are they useful ? ‘Ans. 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 (ora 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 displayed using help( ) function. So, even though docstrings appear like comments (no execution) but these are different from comments. 251. 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 ? ‘Ans. 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 i by Python. ie same program is ignored 252. What would be the output produced by the following cade import math import randon print (math.ceil (random. random())) Justify your answer. Scanned with CamScanner Ans. The output produced would be 1.0 Reason being that random.random( ) would generate 2 number in the range (0.0, 1.0) but math.ceil() will return ceiling number for this range, which is 1.0 for all the numbers yge. Thus the output produced will alw in this ra 253. Consider the following code import math import randoa print(str( int( math.pow( random.randint(2, 4), 2))), end='") print(str( int( math.pow( randon.randint(2, 4), 2))),end=‘') print(str( int( math.pow( randon.randint(2, 4), 2)))) What could be the possible outputs out of the given four choices ? (234 (i944 Gi 161616 (i) 249 (494 ASA Ans. The possible outputs could be (ii), (ii), (2) and (xi). The reason being that randint( ) would generate an integer between range 2...4, which is then raised to power 2, so possible outcomes can be any one of these three: 4,9 or 16. 254. What is the problem in the following piece of code ? from math import factorial print(math. factorial(5)) Ans. In the “from-import” form of import, the imported identifiers (in this case factorial()) become part of the current local namespace and hence their module's names aren't specified along with the module name. ‘Thus, the statement should be : print factorial(5) 255. What is a package ? How is a package different from module ? Textbook Q. 3, Chapter 4 (Type AI] Ans. A module in python is a .py file that defines one or more function/classes which you intend to reuse in different codes of your program. To reuse the functions of a given module, we simply need to import the module using import command. A Python package refers to a directory of Python module(s). This feature comes in handy for organizing modules of one type at one place. 256. What do you understand by standard library of Python ? [Textbook Q. 14, Chapter 4 (Type Al] Ans. A library is a collection of modules (and packages) that together cater to a specific type of applications or requirements. Python standard library is the library, which is distributed with Python that contains modules for various types of functionalities. Some commonly used modules of Python standard library are : math module, emath module, random module, statistics module, Urllib module, etc.. Mi Scanned with CamScanner 5. PUTER SCIENCE (Python) ~ Xil 2 MOVE FAST WITH 257. What is the procedure to create own library/package in Python 2 ‘Ans. To create own library or package in Python, we should do the following - (i) Create a package folder having the name of the package/library (ii) Add module files (.py files containing actual code functions) to this package fold, (iii) Add a special file namely __init_.py to it (even if the file is empty) (iv) Attach this package folder to site-packages folder of Python installation, 258. Suppose thal after we import the random module, we define the following function cated gy in a Python session : [Textbook Q. 6, Chapter 4 (Type By def diff(): x= random. random() - random. random() return(x) What would be the result if you now evaluate y=difF() print(y) at the Python prompt ? Give reasons for your answer. Ans. Variable y would store a non-zero value. This is because, during both executions of random.random( ), a random number would be generated between 0-1 for first execution and successive execution would result in a different random number. Hence a non-zero result . Gan are the possible outcome(s) executed from the following code ? Also specify the maximua fad minimum values that can be assigned to variable NUMBER. STRING = "CBSEONLINE" NUMBER = random.randint(®, 3) N=9 while STRING[N] I= 'L': print (STRING[N] + STRING[NUMBER] + '#", end=' ') NUMBER = NUMBER +1 NeN-2 (i) ESENE#IO# (ii) LEENOON# (iii) NS#IE#LO# (iv) EC#NB#IS# {Textbook Q. 7, Chapter 4 (Type B)] ‘Ans, Part (iv) can be one of the possible outcomes. Maximum value 3, minimum value 0. 260. Consider the following code [Textbook Q. 8, Chapter 4 (Type Bil import random print(int( 20 +random.random() * 5), end print (int( 20+ randon.randon() *5), end print(int( 20+ random.random() *5), end=** ) print (int( 20+ random.random() * 5)) Find the suggested output options (i) to (iv). Also, twrite the least value and highest value that can be generated. (@) 20 22 24 25 (if) 22 23 24.25 (iii) 23.24 23 24 (iv) 21 21.21.21 Scanned with CamScanner 4 e_"”~_-—aMuU—<—<—t—eesefet UNIT PROGRAMMING AND COMPUTATIONAL IHInHGRG (Bor A) of the possible outcomes dom() * 5) Ans. Parts (ii), (fv) ean be on For expression int( 20 + randos ra inimum value 20 Maximum value 24, sion random.random() * 5: xxxxxx (© 5.0), minimum value 00. [Textbook Q. 9, Chapter § (Type fit For expre’ Maximum valu dol, Consider the following, voile Amport random print (100 +random.randint(5, 10), end» '' ) print (100 +random.randint(5, 10), end =" * ) print (100 +random.randint(s, 10), end="') print (100 + random.randint(5, 10)) Find the suggested output options (i) to Civ), Also, write the least value | cam be generated. | (i) 102 105 104 105 (ii) 110 103 104 105, | (iii) 205 107 105 110 (iv) 110 105 105 110 Ans. Parts (ii), (ii), (iv) can be one of the possible outcomes. For expression 100 + random.randint(5, 10) : Maximum value 110, minimum value 105 For expression random.randint(5, 10) : Maximum value 10, minimum value 5 262. What are the possible outcome(s) exceuted from the following code maximum and minimum values that can be assigned to variable PICKER. | [Textbook Q. 11, Chapter 4 Type Bil | import random | PICK = random.randint(@, 3) CITY = ["DELHI", "MUMBAI", "CHENNAI", “KOLKATA™] ; for I inCITy : for J in range(1, PICK) print(I, end="") print( ) ()——DELHIDELHT (ii) DELHE MUNBATMUMBAT DELNTMUMBAT CCHENNATCHENNAT DELHIMUMBATCHENUAL KOLKATAKOLKATA (i) ELA (iv) DELHT MOMBAT MUMBAIMUMBAT CCHENNAT KOLKATAKOLKATAKOLYATA KOLKATA Ans. Part (if) can be one of the possible outcomes, Maximum value 3, Minimum value 0 rT Scanned with CamScanner SS $$ 54 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ xi) 263. What possible outpu(s) are expected to be displayed an screen at the time of execution She Program from the following cole ? Also specify the maximum values that can be signed each of the variables FROM and TO. ICBSE Sample Paper 1929 import random AR = [20, 30, 40,50, 60,70]; FROM = random.randint(1,3) TO = random.randint(2,4) for K in range(FROM,TO+1): print (AR[K],end = "#") (108402708 (ii) 30%40#504 (iii) 508608704 (iv) 40250870 ‘Ans. (if) 30#40#50# Maximum value for FROM is 2.x but <3 and for TO is 4 264. What is the output of the following code ? dnry={@: 'a', 1: 'b', 2: 'c'} for i indnry: print(i) Ans. @ 12 265. (a) What is the output of the following code ? print(x, y) (b) Write corrected code for part (a) so that it prints keys and values both. Ans. (a) The above code will produce Error as we can iterate only on keys in a dictionary. Thus the line : for x, y indnry: is wrong and it will give error. (&) dnry= (0: ‘a', 2: 'b', 2: ‘c'} for xin dary: print(x, dary[x]) 266. What is the output of the following ? dry = {@: ‘a", 2: "b’, 2: ‘c'} for x, y in dry. itens( print(x, y, end=" *) Ans. Oalb2c Scanned with CamScanner UNIT : PROGRAMMING AND COMPUTATIONAL THINKING (Part A) 55, 267. What is the output of the following ? d= (0: 'a', 1: 'b', 2: 'c'} for x ind. keys(): print(d[x] , end =" *) Ans. abe 268. What is the output of the following? d=: ‘a, a: 'b’, 2: 'c'} for xin d.keys(): print(x, ":", dfx], end =". Ans, 0: a. 1: b. 22 269, What is the output of the following ? d={0:'a', 1: 'b', 2: ‘c'} for x ind.values(): print(x, end=* Ans. abc 270. What is the output of the following ? d={@: 'a', 1: "bY, 2: 'c} for x ind.values(): print(d[x]) ‘Ans. The above code will produce Error as dictionary’s values cannot be used as keys ie, inside square brackets. 271, What is the output of the following ? d={0, 1,2} for x ind.values(): print(x) ‘Ans, The above code will produce error as d stated above is not correct form of dictionary, which has keys and values. Programming Questions 272. Write a program to print one of the words negative, zero, or positive, according to whether variable x is less than zero, zero, or greater than zero, respectively. [Textbook Q. 1, Chapter 1 (Type C)] Ans. n= int (input("Enter a number: ")) ifn==0: print("Zero") elifn>@: print("Positive") else: print("Negative” se EEEENpppeper per tar-seser-peumqepummn! Scanned with CamScanner so Mee brtvecrhbotion—-ube. ] 273. Write a program that returns True if the input number is an even number, False othr, FTextbook Q. 2, Chapter 1 (yp¢ Ans. n= int(input("Enter a number:")) def checkEven(n): return ((n%2) == 0) print(checkEven(n)) 274. Write a Python program that calculates and prints the number of seconds in a year. [Textbook Q. 3, Chapter 1 (Type cy Ans. ‘days hours = 24 minutes = 60 seconds = 60 total_sec = days * hours * minutes * seconds print("Total seconds ina year are", total_sec) 275. Write a Python program that accepts two integers from the user and prints a message saying if first number is divisible by second number or if it is not. {Textbook Q. 4, Chapter 1 (Type Ans. x= int(input("Enter first number: ")) y= int(input ("Enter second number: ")) ify==0: print (“Wrong input. Second number cannot be zero") exit(0) ifx%y == 0: print(x, "is divisible by", y) else: print(x, "is not divisible by", y) 276. Write a program that creates alist of all the integers less than 100 that are multiples of 3 or 5. [Textbook Q. 6, Chapter 2 (Type Ol Ans. for i in range(1, 101): Af i%3==O80riks print(4) 277. Define two variables first and second so that first = “Jimmy” and second = “Johny”. Write a short Python code segment that swaps the values assigned to these two varidbles and prints the results, [Textbook Q. 7, Chapter 2 (Type C)] Ans. first = "Jimny" second = "Johny" Scanned with CamScanner UNIT |: PROGRAMMING AND COMPUTATIONAL THINKING (Port A) 57 ARAN COMPUTATIONAL THINKING (Port A 278. 279. 280. 281. 282. i # swap first, second = second, first # print print(first, second) ‘Write rprogram that prints a table ow two columns ~ table that helps converting miles into kilometres, {Textbook Q. 9, Chapter 1 (Type ©) ‘Ans. for i inrange(1, 10): nn L, C print(i, i* 1.6) ° Write another program printing a table with two colunns that helps convert pounds int kilograms. [Textbook Q. 10, Chapter 1 (Type Cl Ans. for i inrange(1, 10): print(i, i* 0.454) Write a function that takes amount-in-dollars and dollar-to-rupee conversion price: it then returns the amount converted to rupees. Create the function in both void and non-void forms, [Textbook Q. 1, Chapter 3 (Type O Ans. def DollarToRupee (dollars, exchangeRate) : return dollars * exchangeRate Write a function to calculate volume of a box with appropriate default values for its parameters. Your function should have the following input parameters (a) length of box ; — (b) width of box; (c) height of box. Test it by writing complete program to invoke it. TTextbook Q. 2, Chapter 3 (Type O] Ans. def volume(length = 1, breadth = 1, height = 1): return length * breadth * height print(volume(1, b, h)) Write function namely nthRoot) that receives to parameters xan n and returns nt oot of x ie, x". The default value of m is 2. Textbook Q. 6, Chapter 3 (Type Ci] Ans. def nthRoot (x, n= 2): return x ** (1/1) Scanned with CamScanner CT MOVE FAST WITH COMPUTER SCIENCE (Python) - Xil 58 TyPG ¢ LONG ANSWER QUESTIONS FEE, 283, Write a program that asks the user the day number in a year in the range 2 to 365 ang asks the first day of the year ~ Sunday or Monday or Tuesday etc. Then the program should display the day on the day-number that has been input. [Textbook Q. 5, Chapter 1 (Type cy, Ans. days = {‘Monday': ®, ‘Tuesday’: 1, ‘Wednesday’: 2, ‘Thursday’: 3, “Friday’: 4, "saturday": 5, "Sunday": 6} n= int(input (“Enter the day of the year:")) (n-1)%7 input ("First day of the year: ") while first not in days: print ("Please enter a correct day with first letter capital, e.g. Monday") first = input("First day of the year: ") current_day = days[first] + added for day in days if days[day] print (day) break current_day: 284. One foot equals 12 inches, Write a function that accepts a length written in feet as an argument and returns this length written in inches. Write a second function that asks the user for a number of feet and retumns this value, Write a third function that accepts a number of inches and displays this to the screen. Use these three functions to write a program that asks the user for a number of fect and tells them the corresponding number of inches. [Textbook Q. 6, Chapter 1 (Type C)] Ans. def feetToInches(n): return n *12 def inputFeet(): return int (input (“Enter height in feet: ")) def displayInches(Anches): print("The height in inches is", inches) displaylnches (feetToInches(inputFeet())) 285. Write a program that reads an integer N from the keyboard com, putes and displa the sum of the numbers from N to (2*N) if Nis nonnegative. If N is a ie ‘umber, then isthe sum of the numbers from (2* N) to N. The starting and ending = are included in the sum, [Textbook Q. 7, Chapter 1 (Type ©] s. N= int(input("Enter Ni ")) step =N// abs(N) Scanned with CamScanner _— roa pratcnsnn temmmcchita (PORT F unit ocrsnsananats 110 CARAS fr sun for tin range (Hs vel pens step, Step)! print (oust) the format manele The v integer in treads a date ao antl Bes A a.ts se ‘rma: ho gus. Write a program thal , wrogrart wil call a function that prints print out U Namex «day, “year: Sample runt Enter date 5 12252019 becenber 25, 2019 FTeathank (2. 6, Chapter 3 re" CH Ane dave = Input ("Enter d def prettyprint (date) : ronths = (1; "January. june", ‘october’, 11; ‘November, ronth = months[ int (datef :21)] day = date[2:4] year = date[4:] prettybate «month +" " + day + print(prettybate) prettyPrint (date) au? Write a program that reads two times in military format (0900, 1790) and prints the number of hours and minutes between the two times. ‘A sample run is being given below + Please enter the first time : 6920 Please enter the second time ; 1738 Bhours 30 minutes late in eDDeCC! Format: ") ‘ 2: ‘February’, 3: ‘March’ » 4: tag! , 52 VOY ssuly! Bi: ‘August’, 9: “Septenber’s 1: 12: ‘December’ } + year [Textbook Q. 11, Chapter 1 Type Cil Ans, time = input("TAme 1: ") time2 = input ("Time 2: ") small = min(int(time1), int(time2)) big= max(int(time1), Ant (time2)) hours =@ minutes =@ while small < bigs small +=1 mints = small % 100 Lf mints == 60: small += 100 small //» 100 Scanned with CamScanner FAST WITH COMPUTER SCIENCE (Python) ~ Xi! small *= 100 minutes +=1 hours = minutes // 60 minutes = minutes - (hours * 60) print(hours, “hours”, minutes, “minutes") 288, Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers, fur ewnple, 017-555-1212 is q legal input. Display if the phone number entered is valid format or not and display if the phone number is valid or not (i¢., contains just the digits and dash at specific places). Textbook Q. 1, Chapter 2 (Type O} Ans phoneNumber input ("Enter phone number: ") def checkNumber (num) : if Len(num) t= 12: return False if num[3] != return False ‘num = num{ :3] + num[4:] if num[6] !=" return False num = num :6] + num[7:] return num. isdigit() if checkNumber (phoneNumber) : print ("Valid") else: print("Invalid”) 289. Write a program that should prompt the user to type some sentence(s) followed by “enter”. It should then print the original sentence(s) and the following statistics relating to the sentence(s) : > Number of words > Number of characters (including white-space and punctuation) > Percentage of characters that are alpha numeric Hints: > Assume any consecutive sequence of non-blank characters in a word, (Textbook Q. 2, Chapter 2 (Type Cl Ans. para = input ("Enter sentence(s) words = @ characters = len(para) allphaNum = @ 4 Scanned with CamScanner PROGRAMMING AND COMPUTATIONAL THINKING (Part A) 61 splittedPara = para.split(' *) for i in splittedPara: file" words #=1 for i inpara: if i isalnun(): alphaNun += 1 print("hords:”, words) print("Characters:", characters) print("Percentage alpha nuneric:”, alphaNum * 188 / characters) Write a program that takes any two lists L and M of the same size and adds their elements together to form a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L=[3, 1, 4] and M=[1, 5, 9] then N should equal [4, 6, 13]. [Textbook Q. 3, Chapter 2 (Type Cll Ans u= (3,1, 4] M= (1,5, 9] An = Jen(L) N=] for ain range(1n): N.append(L[a] +M[a]) print(N) Write a program that rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc, and the element in the last index moves to the first index. [Textbook Q. 4, Chapter 2 (Type ©] Ans. lis = eval(input(“Enter list:")) last =1is[-1] for i in range(len(lis) - 1, @, <1): lis[i] = 1is[i-1] lis[9] = last print(lis) Write a short Python code segment that prints the longest word in a list of words. [Textbook Q. 5, Chapter 2 Type Ol Ans. Lis = input (“Enter a space separated List of words: *).split() longest = “* maxlen=6 for iin lis: if Len(i) > maxlen: maxlen = en(i) longest =i print(longest) Scanned with CamScanner 62 (MOVE FAST WITH COMPUTER SCIENCE (Python) — Xit ——— 293, Write a Python program that creates a tuple storing first 9 terms of Fibonacci Serig [Textbook Q. 8, Chapter 2¢7, eG " Ans. previ=1 prev2=1 Fibs (1, 1,) for { in range(3, 10): hext = previ + prev2 Fib += (next, ) previ = prev2 prev2 = next print (fib) 294, Create a dictionary whose keys are month names and whose values are the number of days in the corresponding months, (a) Ask the user to enter a month name and use the dictionary to tell them how many days are in the month, ()) Print out all of the keys in alphabetical order, (©) Print out all of the months with 31 days, (d) Print out the (key-value) pairs sorted by the number of days in each month, [Textbook Q. 9, Chapter 2 (Type C)] Ans. daysInonths = {'January': 31, "February": 28, 'March': 31, ;"April': 30, ‘May': 31, ‘June’: 30, "July": 31, ‘August’: 31, ‘September’: 30, ‘October’: 31, 'Novenber": 30, ‘December: 31) #PARTA month = input ("Enter month:") while month not in daysTnMonths: print ("Please enter valid month with first letter capital") month = input("Enter month: ") print("The number of days in", month, "are", daysInMonths[month]) # PART B for i in sorted(daysInMonths. keys()): print (i) PART for 4 in daysInMonths: if daysInMonths [4] print(1) PART D for i in sorted(daysInMonths, key = daysInMonths. get): print(i, daysInMonths[4]) Scanned with CamScanner 295, Write a function called addDict(dictl, dict2) which computes the union of two dictionaries. It should return a new dictionary, with all the items in both its arguments (assumed to be dictionaries). If the same key appears in both arguments, feel free to pick a value from either. [Textbook Q. 10, Chapter 2 (Type OL Ans. def addDict (dict1, dict2): newict = (} for i indict: newOict[i] = dict1[i] for i indict2: newict[i] = dict2[i] return newict 296. Write a program to sorta dictionary’s keys using Bubble sort and produce the sorted keys as a list. Textbook Q. 11, Chapter 2 Type 1 Ans. def bubbleSort (arr): for i in range(len(arr) - 1): in range(len(arr) - i - 1): if arr(3] > arr[j +1]: arr[j], are[j +1] =are[j +21, arr] return arr def sortDictKeys(dictionary): return bubbleSort (dictionary.keys()) def sortDictValues(dictionary): return bubbleSort(list(dictionary.values()) 297. Write a program to have following functions = ( a function that takes a number as argument and calculates cube for it. The function does riot return a value. If there is no value passed to the function in function call, the function should calculate cube of 2. (ii) a function that takes too char arguments and returns True if both the arguments are equal otherwise False. Test both these functions by giving appropriate function call statements. [Textbook Q. 3, Chapter 3 Type Cl Ans. def cube(x=2): print(x** 3) def comp(a, b): return a==b cube(5) cube() print(comp(‘a', ‘a')) print(comp('z', "x")) Scanned with CamScanner 64 MOVE FAST WIH COMPUTER SCIENCE (Python) - Xil 208 Write a function that receives two numbers and generates a random number that range. Using this function, the main program should be able to print e numbers randomly. Textbook Q. 4, Chapter 3 eryp, €O) An 1 import random def randomInRange(a, b): return random.randrange(a, b) for { in range(3): print (randomInRange(1, 10)) 299. Write a function that takes a number n and then returns a randomly generated number having exactly 1 digits (not starting with zero) e,, ifm is2 then function a randomly return a number 10-99 but 07, 02 etc,, are not valid two digit numbers, [Textbook Q. 7, Chapter 3 (Type Ans Amport random def randomNDigitNunber(n): um =" firstIteration = True for i inrange(n) randomDi git if firstIteration: randomDigit = str(random.randint(1, 9)) firstIteration = False else: randomDigit = str(random.randint(@, 9)) num = randombigit + num return num print (randonNDigitNumber(7)) 300. Write a function that takes two numbers and returns the number that has minimum. one's digit. [For example, if numbers passed are 491 and 278, then the function will return 491 because it has got minimum one’s digit out of two given numbers (491s 1 is < 278's 8)]. Textbook Q. 8, Chapter 3 (Type C)] Ans def smallUnitPlace(x, y): unit = x% 10 unity = y%10 Af (unitx < unity): return x else: return y | A oUlube ‘Notion Tube ell ami Scanned with CamScanner lun Write 9 program thet generates 2 series using a fancion which tales Grst and last values of the series and then generates four terms that are eqcidisant og. if two numbers passed are Land 7 then fonction retarrs 1357. [Texeok Q 8, Chae: 3 Type C1 return (a, 344, 262%¢, 26 3°S,) print (completeSeries(2, 7)) Create a module lengthoonversion py that stores Sanctions for warious lengths CONVETSON LH (Teabeuk Q. 1 Chapter 4 Type O1 > miktokm() to convert miles to Kilometer > kmtomile() to convert Kilometers to miles > feettoinches) > inchestofeet{ ) It should also store constant values such as value of (fle in KSlameters and vice versa} [I nile = 1.629368 ktlometer ; 2 feet = 22 inches] Help ) function should display proper information Ans slengthconversion.py *' "This module stores various conversion functions: to convert distances into different units*** def niletokm( 6): 3 conversion function 2 *retums miles converted to kilometers*** return 6 * ONE MELE def tntonile( ): 3 conversion function 2 ** "returns idlometers converted to miles return d / ONE MCLE def feettoinches( In): # conversion function 3 ***metums feet converted to inches*** retuma In * ONE_FEET def inchestofeet( In): conversion function $ ***retumns inches converted to feet*** return In / ONE_FEET ‘teomstants ONE_MILE = 2.608344 221.620 ONE_FERT = 12 $= i2inches Scanned with CamScanner MOVE FAST WITH COMPUTER SCIENCE (Python) - Xil 303. Create a module MassConversion.py that stores function for mass conversion eg) > 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. [Textbook Q. 2, Chapter 4 (Type gy Ans. #MassConversion.py “"'This module stores various conversion functions to convert masses into different units’ ** def kgtotonne(m): # conversion function 1 “* "returns kilograms converted to tonnes* ‘* return m* ONE_KG_TONNE def tonnetokg( m): # conversion function 2 “**returns tonnes converted to kilograns return m / ONE_KG_TONNE def kgtopound( m): # conversion function 3 ***returns kilograns converted to pounds''* returnm* ONE_KG_POUND def poundtokg( m): # conversion function 4 “* "returns pounds converted to kilograms’ ++ return m / ONE_KG_POUND #constants ONE_KG_TONNE = 0. 881 #= 0.081 tonne ONE_K6_POUND = 2.26462 2.20462 pound Scanned with CamScanner “yw IIL pata Management (SQL, Django) this Unit Chapter 13 Chapter 14 Chapter 15 Chapter 16 (For Examination Question No. 4) MySQL Revision Tour More on SQL Creating a Django based Basic Web Application Interface Python with MySQL YouTube :Notion Tube Scanned with CamScanner 202 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ Xil GLIMPSES —~< Database. It refers to collection of logically related data. 5 Data Redundancy. The duplication of data is known os data redund ¢ = irons: i mismatching copies of same data repeat Hata Pees pret fa against accidental or intentional discos Peale, ised modification or destruction. we to mathe + ahien B ; Baa Privacy. Rights of individuals and organizations to determine forth at extent information about them is to be transmitted to other. 8h . | Wang Data Independence. Abitit i In : ty to modify a scheme definition i ‘i definition in the next higher level. nition in one level without affecting a5, ~ Relational Data Model. The data model wherein the data is organize . wherein the data is organized i ; , d e ized into tables called Relationship among multiple tables is established on the basis of common ei _ > Relation. A table having non-empty atomic values with unordered rows and columns is a rela relation, + Domain. A pool of values wherefrom a field can draw values is called domain, ~ Tuple. A row in a relation is called tuple. 4 Attribute. A column in a relation is called attribute. Degree. Number of attributes in a relation is called its degree. © Cardinality. Number of tuples in a relation is called its cardinality. Primary Key. A set of one or more attributes that can uniquely identify tuples within the relation, » Candidate Key. All attribute combinations inside 2 relation that can serve as primary key. + tues are derived from the primary key of some other Foreign Key. A non-key attribute whose val table. 4 SQL. Structured Query Language. A ron-procedural UGL used for querying upon rlafon! databases. DDL. Data Definition Language. SAL pat tc. of database objects such as tables, DML. Data Manipulation Language, SOL Jéeletion / modification) of data residing in database Metadata. Facts/data about the data stored in tables. ‘A file containing metadata. ; | t that stores a web applica kage (a directory 0} tanguage that facilitates det indexes, sequences etc. ri-language that facilitates ma tables. fining creation/modification niputation (2déition | | tion’s data and relationships. rains all the settings ¥f code) that cont ~ Data Dictionary. _s Model. A componen' + Django project. A Python pac instance of Django. part of Django proj ‘A chunk of text for 30 als with one subpart of the project. rect that specifically de ata. that acts as formatting View (In Django context): ‘A function responsible for rendering a sas opatioae F ic sites, development of dynam ftware tool that supports the Web framework. A 0 web applications. ee $F ae for representing 4 Template. Scanned with CamScanner LNT IIL DATA MANAGEMENT (S01, Django) 203 OBJECTIVE TYPE Qu ESTIONS Tis Multiple Choice Questions See relational database consists of a collection of : a qables (b) Fields. (© Records @ Keys a relational database consists of a collection of > a Toples (b) Attributes (©) Relations (@) Keys a(n) _— in. table represents a logical relationship among a set of values. (@) Attribute (b) Key (c) Tuple (@) Entry 4, The term is used to refer to a record in a table. (a) Attribute (b) Tuple (© Field (@) Instance = The term is used to refer to a field in a table. (a) Attribute (b) Tuple (©) Row (@) Instance « A___isa property of the entire relation, which ensures through its value that each tuple is unique in a relation. (a) Rows (b) Key (©) Attribute (d) Fields 7, Which of the following attributes can be considered as a choice for primary key ? (@) Name (©) Street (© Roll No (@) Subject Which of the following attributes cannot be considered as a choice for primary key 2 (Id (B) License number (©) Dept_id (@) Street 9, Anattribute in a relation is a foreign key if tis the key in any other relation. (@) Candidate (b) Primary (© Super (a) Sub 10. Consider the table with structure as : Student(ID, name, dept name, tot_cred) In the above table, which attribute will form the primary key ? (2) Name (b) Dept (0) Total_credits (a) ID The operation whose result contains all pairs of tuples from the two relations, Tegardless of whether their attribute values match. , (@) Join (b) Cartesian product (©) Intersection (d) Set difference 12 What is the full form of SQL? (@) Structured Query Language (&) Structured Query List (© Simple Query Language (@) None of these 1 5 5. What isthe full form of DDL ? (©) Dynamic Data Language (b) Detailed Data Language (9 Data Definition Language (d) Data Derivation Language Bie Scanned with CamScanner 204 MOVE FAST WITH COMPUTER SCIENCE (Python) MOVE FAST WITH COMPUTER SCIENCE (Pytn >... 14. What does DML stand for ? (a) Different Mode Level (b) Data Model Language (©) Data Mode Lane (d) Data Mani = 5g : é g 2 @ Q a 8 e z 5 & a £ c z 2. 3 including tables ? (a) Data Definition Language (DDL) _(6) Data Manipulation La (6) Both (a) and (b) (@) None 16. Which of the following sublanguages of SQL is relation, deleting relations and relating schemas? "BBE (Oy) sed to define the stricture of the (@) DML (Data Manipulation Language) (#) DDL (Data Definition Language) (© Query (@) Relational Schema 17. Which of the following sublanguages of SQL is used to Query information from tig Gatabase and to insert tuples into, delete tuples from, and modify tuples in ihe database ? (@) DML (Data Manipulation Language) (6) DDL (Data Definition Language) (©) Query (@) Relational Schema 7S, Consider following SQL statement. What type of statement is this ? CREATE TABLE employee (name VARCHAR, id INTEGER: ) (@) DML (6) DDL (¢) DCL (d) Integrity constraint 18. Consider following SQL statement. What type of statement is this? SELECT * FROM employee () DML () DDL (9 DCL (@) Integrity constraint 20. ‘The data types CHAR(n) and VARCHAR(n) are used to create and types of string/text fields in a database. (@) Fixed, equal (b) Equal, variable (©) Fixed, variable (@) Vatiable, equal 21. A table Table has two text fields defined as below : Namet varchar(28), Wame2 char(20), If Namel stores value as ‘Ana’ and Name2 stores value as ‘Anuj’, then Namet will consume characters’ space and Name2 will consume characters’ space. (@) 3, 20 © 20,4 (© 20, 20 (3,4 Scanned with CamScanner | UNIT IIl__DATA MANAGEMENT (SL, Django) 205 jor fll SQL statement. What type of statement is this ? con side e o instructor VALUES (10211, ‘Shreya’, ‘Biology’, 66000); nseRT INT () DML (ove (@ pot procedure ay Pree .e following keywords will you use in the following query to display the cof th which ot os of the column dept_name? via meet dept_name FROM Company; yall (b) From (c) Distinct (@ Name wa 1 of the following keywords will you use in the following query to display all si WME ges ofthe column dept_name 7 the vale’ SELECT dept_name FROM Company; wal (b) From (0) Distinct (@) Name clause of SELECT query allows us to select only those rows in the result thot satisfy a specified condition, (a) Where (b) from (©) having, (d) like 4. _dlause ofthe following query must be added with keyword > Fo felds given in the select list as per a given condition. The —— to display SELECT ID, name, dept name, salary *1.1 WHERE instructor; (@) where, having (B) select, from (0 where, from (@) where, select 2. Which of the following queries contains an error? (@ Select * from emp where empid = 10003; (b) Select empid from emp where empid = 10006; (6) Select empid from emp; (@) Select empid where empid = 1009 and lastname = ‘GUPTA’; 3. Consider the following table namely Employee : Employee_id Name Solary 1001 Misha 6000 1009 Khushi, +4500 1018 Japneet 7000 Which of the names will not be displayed by the below given query ? st ELECT name FROM employee WHERE employee_id>1009 5 (@) Misha, Khushi (b) Khushi, Japneet (© Japneet (d) Misha, Japneet NS YouTube :Notion Tube Scanned with CamScanner =... i inserted ? 200 ove FAST WITH. computer Scie sword has to be tn the given query WHIT keyword has to be nsent INTO employee) —— (1002, Kausar , 2000) 5 I (b) Values le «ta & {@) Relation (id Field Consider the following query + id SELECT name, instructor name, course FROM instructor; To display the field heading course with a different heading as id, which keywory used here to rename the field name ? must be (b) Rename (c) As (d) Join (a) From Si. Which operator performs pattern matching 2 (a) BETWEEN operator (b) LIKE operator (0) EXISTS operator (a) None of these Consider the following query SELECT name FROM class WHERE subject LIKE * Computer Science’ ; Which one of the following has to be added into the blank space to select the subject which has Computer Science as its ending string ? @s O)- oll (a) % Which operator tests column for the absence of data (He NULL value) ? (a) EXISTS operator (b) NOT operator {¢) IS operator (d) None of these 34. Consider the following query SELECT name FROM class WHERE subject _NULL} Which comparison operator may be used to fill the blank space in above query? @= () LIKE os (@ IS NOT 35. The pattern ~~~" matches any string of three characters. '~ -~%' matches any string of three characters. (a) Atleast, Exactly (&) Exactly, Atleast (6) Atleast, All (@ All, Exactly 36. With SQL, how do you select all the records from a table named “Students” where the value of the column “FirstName” ends with an “a” ? (a) SELECT * FROM Students WHERE First (Name = ‘a’ (b) SELECT * FROM Students WHERE FirstName LIKE ‘a' (c) SELECT * FROM Students WHERE FirstName LIKE ‘%a’ (@) SELECT * FROM Students WHERE FirstName = "%a% 37. InSQL, which command is used to SELECT only one copy of each set of duplicable ro" (@ SELECT DISTINCT () SELECT UNIQUE ° Sel (©) SELECT DIFFERENT (@ All of the above Scanned with CamScanner unt I DATA MANAGEMENT (SL. ojang9) 207 “«_ consider the following query ELECT name FROM student WHERE subject = “Physics” ORDER BY name he above query will lists result inorder of - (a) Descending, subject (b) Ascending, subject {o) Descending, name (@) Ascending, a jo. By default, ORDER BY clause lists the results in i —__ order. (a) Descending) Any a sa hon yo. Consider the following query SELECT * FROM employee ORDER BY salary nme To display the salary from greater to smaller and name in alphabeti f i the following options should be used ? ae (a) Ascending, Descending (b) Asc, Desc (0) Desc, Ase (@) Descending, Ascending 41. Select correct SQL query from below to find the temperature in increasing order of all cities. (a) SELECT city FROM weather ORDER BY temperature ; (b) SELECT city, temperature FROM weather ; (0 SELECT city, temperature FROM weather ORDER BY temperature ; (@ SELECT city, temperature FROM weather ORDER BY city ; 42. Which SQL function is used to count the number of rows in a SQL query ? (@ COUNT() () NUMBER( ) (9 SUM() (@ COUNT(’) With SQL, how can you return the number of not null records in the Project field of “Students” table ? (a) SELECT COUNT (Project) FROM Students (b) SELECT COLUMNS(Project) FROM Students (0 SELECT COLUMNS(*) FROM Students (@ SELECT COUNT(*) FROM Students Which of the following is not an aggregate function ? (0) Avg, (W) Sum (© With (@ Min . All aggregate functions except ignore null values in their input collection. (2) Count(attribute) (b) Count(’) (©) Avg (@ Sum | 46. Which of the following is a SQL aggregate function ? | (@) LEFT (b) AVG (¢) JOIN (@ LEN 47. Which of the following group functions ignore NULL values ? (@) MAX () COUNT (SUM (@ All of the above 48. The HAVING clause does which of the following ? | (a) Acts EXACTLY like a WHERE clause. Scanned with CamScanner 208 49. 50, 51 53, 56, 57. 58, » Which option do you use with django. MOVE FAST WITH COMPUTER SCIENCE (Pvhon) = MU (0) Adts like a WHERE clause but is used for columns rather than groups b) Acts like a la (6) Acts like a WHERE (@) Acts like a WHERE clause but is used for rows rather than columns il) Acts like a wise but is used for groups rather than rows, Aggregate functions can be used in the select list or the statement They cannot be used ina ___ clause, (a) Where, having (b) Having, where (©) Group by, having (©) Group by, where SQL applies conditions on the groups through clause after groups haye been formed, (a) Group by () With (0) Where (@) Having Which clause is used with “aggregate functions” ? (@) GROUP BY () SELECT () WHERE (@) Both (a) ana (y 2. What is the meaning of "HAVING" clause in SELECT query ? (0) To filter out the summary groups () To filter out the column groups (© To filter out the row and column values (@) None of the mentioned Where and Having clauses can be used interchangeably in SELECT queries ? (a) True (b) False (0) Only in views (© With order by What are the advantages of using Django for web development ? (0) I facilitates you to divide code modules into logical groups to make it flexible to (©) It provides auto-generated web admin to make website (©) It provides pre-packa (@) All of the above The architecture of Django consists of (@) models administration easy iged API for common user tasks (©) views (6) templates (4) all of these admin to create project in Django? (©) createproject (a) startproject with Python command to start a new (2) newproject () myproject What is the Django command used ‘list’ in an existing project ? (2) manage.py ~newapp list (6) manage.py newapp list (© manage.py -startapp list (d) manage.py startapp list app named . What is the purpose of settings py 2 (@) To configure settings for the Django project ©) To configure settings for an app (©) To set the date and time on the server ( To syne the database schema Scanned with CamScanner moO DATA MANA Ege OL, Oy mg) att the DNB HOHE meth m aed 0 mon a) wnder to. htm Cally yon, der g en, ieee ‘i bel bm Tesponse 2 _ ) rendgy PON what fs the defOult POEL Used by ya IN Websoryo, (a 800 (h) 8000 a a °f Django gy What is the default URL of your Dhan pr (d) 90 jocalhost:8000 (b) oe ei (b) locathost i (1)127.0.0.1:8009 task man, > What is the name OF the administrative (2) manage.py () urls.py + What is the name of the tunetions 2 BEMEN file in Django Projects ? (©) views.py (@) models.py *PP module in Django Projects that stores the view (4) nage py (0) urls.py (©) views.py (4) models.py What is the name of the URL Conts 2 js? (4) models.py “hod for fetching records from database from module in Django projects that stores (2) manage.py © views py () urlspy oo Which of the following is not within Python? (2) tetchone( ) a legal me () fetchtwor ) (©) fetchali( ) (@ fetchmany( ) Fill in the blanks a ss Adatabase controls the a database connecte uunigue session with a connection to the database. It represents a 'd from within a script/program, IS a special control stra cesing of records in the resultset, ie, th S The refers to a logical set of record: evexuting an SQL query and made availabl NUL stands for A connectivity package such as connectivity Python code. cture that facilitates the row by row w set of records retrieved as per query. s that are fetched from the database by le to the application program, | Query Language. must be imported before writing database —— method establishes a database connection from within Python, ——— Method creates a cursor from within Python. ——— Method executes a database query from within Python. The SQL keyword is used to specify the table(s) that contains the data to be Tettieved, , if Tormove duplicate rows from the result of a query, specify the SQL qualifier \ 7 select list - in the Zoe al columns, use a(n) _ instead of isting all the column names Re Scanned with CamScanner - Xi 210 wove Fast wi comPUTER SCIENCE Pvnen! J [7 The SQL clause contains the condition that specifies which rows are oy selected. result table, the ___— clause is specified, can be sorted in descending sequence by using the SQL Keyword t both be true for the rows to be selected, the conditions Fa | re To sort the rows of the Column When two conditions must separated by the SQL keyword . To refer to a set of values needed for a condition, we can use the SQL operat, sv 8 To exclude one or more values (a list of values) using a condition, the SQL keyworg should be used. 83. The SQL keyword is used in SQL expressions to select based on pattems, S4. The SQL built-in function totals values in numeric columns. 85. The SQL builtin function ____ computes the average of values in numeric columns. 86. The SQL built-in function obtains the largest value in a numeric column, 87. The SQL built-in function _____ obtains the smallest value in a numeric column, 89, The SELECT clause is used to collect those rows that have the same value ina specified column. True / False Questions 88. The SQL built-in function computes the number of rows in a table, | | 90, The condition in a WHERE clause in a SELECT query can refer to only one value. 91. SQL provides the AS keyword, which can be used to assign meaningful column names to the results of queries using the SQL built-in functions. 92. The rows of the result relation produced by a SELECT statement can be sorted, but | only by one column. | 93. SQL is a programming language. 94, SELECT DISTINCT is used if a user wishes to see duplicate columns in a query. 95. The HAVING clause acts like a WHERE clause, but it identifies groups that meet criterion, rather than rows. | 96, The qualifier DISTINCT must be used in an SQL statement when we want t0 eliminate duplicate rows. | 97, DISTINCT and its counterpart, ALL, can be used more than once in a SELECT statement. DISTINCT and its . - a is its counterpart, ALL, can be used together on single field in a SELECT 99. COUNT(field_name) tallies only coun those rows that contain a value; it ignores all null z- aid Scanned with CamScanner qe SQL statement yr tes r tal FR (NF lary ane comm OM each row together and Het age Roe EMP? Adds two fields Total the results in a column named “oy ORDER BY can be combined with the SELECT statements, pata manipulation language (OML) comm creating, altering, and mands are used 5 The SQL Keyword GROUP BY instructs the DBM HS we the same value in a column, "Sto group together those rows that » keyword BETWEEN c: i ae The keywe 'N can be used in a WHERE clause to refer to a range of values. ANSWERS 1p Choice Questions 2@ 2 @ +e &@ ‘ &@ 20) 1 © 2 wo B®) 16 @ (a) ata 20. ©) ® 2e © x 26. () @ 28 (a) e Mm zw (6) HOO ° % 0) - BO. - 2 8) wo © 6 @ 48 Bo 50. (@) @ 2) © xe BO 36.) @ BO . @) ae a @@ 2 @ © a ® Flin the Blanks connection object 67. Database cursor 6S. resultset ®. Structured 70. mysql.connector TA. connect() 72. cursor) 73. execute() 74. FROM. 73, DISTINCT — 76. asterisk (") 77. WHERE 78% ORDER BY 79. DESC 80. AND 81. IN $2 NOTIN: 8& LIKE &. SUM ‘85. AVG 86. MAX 87. MIN, 88% COUNT 9. GROUP BY Tue / False Questions MF a. T 92. OF 9 OF OF 6 T cont 97. «iF 98. OF oT 100. T 101. T | mT 103. F 104. F 105. T 106, T | | Very Short Answer Questions Very Short Answer Luestions | \Y. What is relation ? Define the relational data mee. (CESE DQ} | | Ans. Relational Model. The relational model represents data and relationships among, data by a collection of tables known as relations, each of which has a number of columns with unique names. Scanned with CamScanner python) - Xt 312, move FAST COMPUTER SCIENCE (OM = MI FAST WITH CX — lems associated with it ? 10S. What és data redundancy ? What are the p70 cy. It leads to the problems like wastage of I etre eetetrrmnesinseraene erat en ena } | | | | \ns. Duplication of data is data redundan space and data inconsistency: ency ? 109. What is data incon Ans. The problem of data inconsistency. It Which subdivision of SQL is used to put val guage (DML) sed to create tables, mismatched copies of same data, in a database is cag, ervised data redundancy. ple the result of unsupt my Hues in tables and which one to create tables > Ans. Data Manipulation Lan is used to put values in tables and Det, Definition Language (DDL) i What is wrong with the following statern SELECT * FROM Employee WHERE grade = NULL 5 Write the conected form of above SQL statement. Ans. A relational operation ‘~’ is not used with the NULL clause. The corrected form is SELECT * FROM Employee WHERE grade is NULL 5 What is the different between WHERE and HAVING clause ? ions on groups in contrast to WHERE clause, rm went ? 112, Ans. The HAVING clause places conditi which places conditions on individual rows. What do you understand by Degree and Cardinality of a table ? Ans. Degree. Number of columns or attributes or fields in [CUE Sample Paper 2 a table are called table's degree. Cardinality. Number of rows/tuples/records in a table are called table's cardinality For example, for a table shown below + Good learning Smile easy Ho U 4 (Acolumns) Its degre Cardinality is 3. (3 rows) Differentiate between Candidate Key and Alternate Key in context of RDBMS. 1d, {CBSE OD 8} Ans. Candidate key. 4 candidate key is the one that is capable of becoming primary ., a field or attribute that has unique value for each row in the relation. key A candidate key that is not a primary key is called an Alternate Key. 115. What is an Alternate Key ? [CBSE D 8) en A capil bey Be is nota primary key is called an Alternate Key. In Supplier ¢ if there are 2 candidate keys ~ Suppld and Supp_N . Key then Supp_Name is the alternate ey. eine renee YouTube :Notion Tube Scanned with CamScanner | | | 1 bata NANACE Ve ——s NT (Seu, what are DDL and DML 2 Pre) 213 ‘6 Both DDL and DML are soy (cast ¢ Ans compo 3D 06, 92 1904 provides statements for the creation, Serie The DDL (Data Dee 1 views etc. ‘ation and deletion Of tables, Language) indexes, (Data Mi The DML ( " fa Manipulation Language) Provides stay data and perform complex queries on there tables, EMS to enter, update, delete = What do you understand by the terms Prima 0 jataase ? "Y Key and Deg ee Of a relation in relational (CBSE D 05) 7 Fi * BrOUP of attributes Whose values can uniquely ans. Primary key is an attribute o identify the tuples in the relation, Degree. Number of attributes in a relation are called its degree, 11s Want do you smderstand by the terms Candia relational database ? late Key and Cardinality of a relation in Ans. Candidate key. A candidat anaes key ie, a field or attribute that 119, What isa relation ? What isthe differ 12. without affecting its base table. 121, The SQL SELECT provides clauses names of clauses for these, ‘sns. The ORDER BY clause of SQL SELECT statement allows to sort the data of resultset The GROUP BY clause of SQL SELECT statement allows to create summarized results of grouped data from table. What are different types of SQL. functions ? Ans, Jor sorting data and for summarizing results. Write the 1m, ® Single Row (or Scalar) functions. > Multiple Row (or Group or Aggregate) functions. ( Single Row Functions work with a single row at a time. A single row function returns a result for every row of a queried table. ‘ ir ime and (i) Multiple Row or Group Functions work with data of multiple rows at a time an¢ tetum aggregated value. i the employes, Write a query to display the Sum, Average, Highest and Lowest iene 3 employ Ans, mysql> SELECT SUM (sal), AVG (sal), MAX (sal), MIN (sa FROM empl ; | 1, Scanned with CamScanner 24 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ XII 124, Write a query to display the Sum, Average, Highest and alary of th srouped by department number. ve empl Ans. mysql> SELECT SUM (sal), AVG (sal), MAX (sal), MIN (sal) FROM emp] GROUP BY deptno ; 125. Write @ query to display the Sum, Average, Highest and Lowest salary of th Srouped by department number and sub-grouped by job. * eroyey Ans, mysql> SELECT SUN (sal), AVG (sal), MAX (sal), MIN (sal) FROM emp GROUP BY deptno, job ; 126. Write a query to display the number of employees with same jo. ‘Ans, mysql> SELECT COUNT(*) As "No_of_Emps", job FROM emp GROUP BY job ; 127. Write a query to display the difference of highest and lowest salary ofeach depart having maximum salary > 4000. ea Ans. mysql> SELECT MAX (sal) —MIN (sal) “Difference” FROM empl GROUP BY deptno HAVING MAX (sal) > 4000 ; 128, Write a query that counts the number of salespeople registering orders foreach dey. salesperson has more than one order on a given day, he or she should be counted only once), SELECT ord_date, count (DISTINCT salesman_code) FROM orders GROUP BY ord_date ; 129, Write Django command to create a Django project namely easysell. Ans, django-admin startproject easysell. 130. What is web framework ? ‘Ans. A web framework is a software tool that provides a way to build and run dynamic websites and web-enabled applications. 131. What is Django ? Ans, Django isa free and open source web application framework, written in Python. I is a server-side web framework that provides rapid development of secure and maintainable websites. 132, What is a model in Django setup ? Ans. Model is data model basically. It contains everything related to data i.e, what how to access and validate it, relationships among data etc. So, model defines the data access layer in a Django setup. Ans. 133, What is the role of file models.py in Django setup ? Ans. The models.py defines and stores the data models for a project. The models.py specifications are internally extended as full database tables. 134, What is the use of urls.py file ? Ans. This file stores the URL patterns through regular expressions. ad Scanned with CamScanner > ¥ ULL | DATA MANAGEMENT (SQL, Ojongo) 215 Vuh 2 the vole of lewsgry ? sh Fw ciaespy is the actual processing file of Django, which resolves http oa ‘nae for web applications. esq 0 sv ile (ven empty) anal Be part af project folder to make it an importable package ? M wo tnt py le un ets vespenade for carryhg ont ainistrative work of Django project ? ne mANABEPY Wat dn he mignfiennc af et ngs. file ? 11 store» all the configuration settings of a Django project-apps in the project, project, urls configuration etc. hi Ane alatabanes In the What fs the derence betreen a Django project and apps ? Ane A Django project signifies an overall web application while an app is a component ff a project that earres out a distinct function. w {project ean have multiple apps in it hueuty the URL formed by following URL Conf in urls.py, considering the default URL woth default port of buill-In twebserver, (i) path(*home/", views.main) (ii) path( "home/check/' , views. newone) il) path('check/", views.onenew) (iv) path('check/home/", views.core) ‘Ans. (1) localhost:8000/home/ (ii) localhost:8000/home/check {ill) localhost:8000/check/ (iv) localhost:8000/check/home/ HMI Identify view functlons from the following URL confs and write their function headers. (i) path(‘home/", views main) (li) path(*home/check/", views .newone) (ii) path('check/", views-onenew) (iv) path(' check/home/", views .core) ‘Aw, View functions will be inside views.py and their headers will be : (i) def main (request) : (li) def newone (request) + (ill) def onenew (request) + (iv) dof core (request) : 142 Name the files that are found in project web application folder. Ano. _Anit_.py, settings.py, urls.py, wset-py 143, Name the files that found in app folders by default. Ano _Antt_.py, admin.py, apps.py, models.py, tests.py, views PY Write a command to create a Django project MyProject. Ann. dfango-adnin startproject MyProject. Bi” Scanned with CamScanner = 216 Move FAST wit COMPUTER SCIENCE (Python) - XL ———_ 115. Write commands to add two apps to your Djange Project. The apps names are Ft, secondapp. ‘Ans. python mana} python manage.py startapp second app of HTTP requests ? ige.py startapp First app A Django project can make which #00 types Ans. HTTP GET and POST requests wel of Django projects is known as 147, The software architecture mo Ans. MVT (Model View Template) model OR MTV (Model Template View) model The apps of @ Django project must be registered after creating them. Which seting 4 settings.py file is used for this ? ‘Ans, The INSTALLED_APPS setting 149, Within Django project, which HTTP request sends no data to server ? Ans. HTTP GET request. 150. What is URL conf in a Django project ? ‘Ans, The mapping between URL path to the views of Django Project are called URL Confs (URL configurations). The views of Django project are python functions, 151, What are Django project views ? Ans. Django project views are Python functions that get HTTP request type in the form of mandatory argument request (HTTP request type). 152, What is URL routing ? ‘Ans. URL Routing is a process of resolving and mapping URLs through URL Confsin urls.py to actual templates which can be displayed in the web browser as a web page. 153, What is database connectivity ? Ans, Database connectivity refers to connection and communication between an application and a database system. 154, What is Connection ? What is its role ? Ans. A Connection (represented through a connection object) is the session between the application program and the database, To do anything with database, one must havea connection object. 155, What is a resultset ? Ans, A resultset refers to a logical set of records that are fetched from the database by executing a query and made available to the application-program. 156. Which package must be imported in Python to create a database connectivity applicatio eas: There are multiple packages available through which database connectivity __ applications can be created in Python. One such package is mysql.connector. 157, pases do you use for connecting to a data from within Python ? m ft connect() function can be used to connect with a database from within Pythom. 5 t , ch method creates and returns a cursor object that may be used to execute SQL commands ? Ans, The cursor method of connection abject, i, connection.cursor( ) method. Scanned with CamScanner a, | Bonga) dy - CO DATA MANAGEMENT (96 7 whic method is used to execute an SQL commant 1 f ie cursor.execute( ) method, Wi thrwigh a eureop object want does cursor fetchall( ) method do? wt 1 tereturns/fetches all (remaining) rows of «query Fentll, Inthe form a Py aia wil be the generated query string ? munya INSERT INTO DOOKS (LILLE, tsb) VALU, "INSERT INTO books (title, 1sbn) vaLuEs; il yer Ans. | nich record ill get inserted ithe table by the We 8)". Us haa, Ta6 ANB ION6" ("Ushakaal', 1267H9H70%0')" following code 2 {pport nysa connector as sqltor eons stor comect(host = “Local host! , meson = Aycon curso") query g "INSERT INTO books title, {sbn) VALUES(Ks, X+)",X (‘Ushakaal? 12678087036") ‘qursor execute (query) ycon-commit() User = "Learner, parsed = “fast”, databaxon" ns. ‘Ushakaal', 12678987036 What will be the generated query string ? 163 query « “INSERT INTO books (title, Abn) VALUESC®()", ())". format “ushakinan! 4 m0) Ans. “INSERT INTO books(title, isbn) VALUES('Ushakiran' , '42568987036')" 64. What does connection.commit( ) method do? ns. This method commits the current transaction in the physical database, Without this, even after successful execution of query, the changes are not reflected in physical database. 165 returns how many rows have been so far retrieved using fetch-methods, Ans. cursor.rowcount 170 6 SHORT ANSWER QUESTIONS i 166. Givw a suitable example of a table with sample data aud iustrate Primary and Candidate Keys in it {CBSE D 12, 061 Ans. Candidate key. A candidate key is the one that is capable of becoming primary key i, a field or attribute that has unique value for each row in the relation. Primary key is a designated attribute or a group of attributes whose values can ‘uniquely identify the tuples in the relation, Example : Table: Class 11 Admo. RoltNo Nome Marks. 10 1 Rahat 5 1083, 2 Irfan Ey 2011 3 Maya 63 11000 4 Shaun 999 5 ‘Sukhi 2 1200 6 Zoya 86 Scanned with CamScanner an MOVE TANT WIN COMPUTER BEIENEE (Python) — IL tn the above table, column AdhHNo and RotINe have unique both are eanalidaten to bocome primary keyr, Hnce both of the Keys: Ont af thee tivo, we ean amalgn one an primary fe alternate key, Candidate hoy! AdmNo, RollNe RollNo Mleruate keys AdmNo Give a sulable evumple ofa tulle aith ni Vilii04 FO way ine Cotten i MANY Cong ry AN Ue othiey Mig one wi lt My Primary hs sme taal strate Primary an Mernatey, CUBE OD iy 5% Ane Primary Key. Ww the wet of one ar more altrbuten hat con ung iden tuples within a relation, Alternate Example : Key. Wa candidate key which tn not primary key, Table t Clay 1 Marks _| wou Rahat as tou Infan * 201 Maya 6 100 Shaun 99 Sukhi ” 1200 In the above table, columns AdmNo and Roll both are candidates to become Keys. Out of these two, we Alternate key, Candidate keys: AdmNo, RollNo Primary ke RollNo Alternate key: AdmNo Mo you wnterstand by Candidate from a table containing Ans. A table a tuple uniquel No have unique values foreach row, ap Primary keys, Hence both of thene columng are Candidate Can assign one as Primary key andl the other one will become 168, What keys "ys ina lable 2 ¢ some meaningful data, may have more y, all such attrib ‘lve a suitable example of Candidate ICBSE D 10, 09] than one such attribute/group of attelbutes that Identifes ‘te() are known av candidate keys, CANDIDATE KEY Scanned with CamScanner UHM DRI TAMIWASRIARIAN U86e tepanagy ua vc unerstanul by Primary Beyy © ales a ott sive w omttahle esanyle of Pornoary Beg pron al i iy ume ineatingfi at “I OWE OT 1H, 4, 7) wnat! te [pany Key 4 seh oF 8 Fron aie tal can iquy wsntiy Ma ‘ w porexample In the following, table Btudent, the column Halling ran noiguedy iAeniity frei the able, Het Rollo te the primary hey of the follaying, table Fr 4 = fling | _—_ Name tne | 7 i 1 ee | sian product of tow relation fonse OD OF Explain Cate ang Te cartesian produc! {8 a binary operation and ts denoted hy a erase (4). hee an product of two relations A and B la walle as Ae 8 The cartesian product ‘new rejation which has a degree (number of attributes) equal the suas of thee 2 ifthe two relations operated upon, The number of ples (cardinality) of thie ne” ict of the number of tuples of the two relations operated upon Ie two relations yields a relation with all possible combinations af he f ca yields ‘dogree relation is the prod cartesian product of tuples ofthe two relations operated upon. For example of Cartesian product see the following, question, (1 174 below) iri. What do you wnderstanl by Union and Cartesian Product erations performed upon to relations ? ICHSE Sample Paper H1, 12, CBOE D 1, OD OH ‘Ans, Cartesian Product, The Cartesian product of two relations A and It vite AB The antesnn product of two relations yields a relation with all possible combinations of the tuples of the two relations operated upon. eg, given two relations Student and Instructor as shown below Studont Instructor ‘Study Stud-Nome _Hosteler Tnstd__Inst-Name _ Subject. S001 Meenakshi Y i K. bal English 002 Radhika N 102 Rul Arora _ Maths $003___Abhinav N as The cartesian product of these two relations, Student x Instructor, will yield a relation Tae [steanane [toate [ts | trttome | Sie soon | Meenakshi Y tot K. Lal English ‘S001 ‘Meenakshi Y 102 RA. Arora ‘Matt 002 Radhika N ior K. Lal Englioh so02 | Radhika N 2 Ru. Arora | Maths $003 | Abhinav N tol K. Lal English Abhinav n | m Ru. Arora | Mathie Scanned with CamScanner 22 XRUE PARE AIL CO NUITER BEIEKCE (Pin) ' Uni, Ue ss poration proties HMeE ela th thal votes play fo the oye latvia at wi HT lai Te yon ot vlan Nand Vs ave wyatt NF Vavtlele tll contain all tijden nt Hal ap yoaticnny Nat oe wit Ir cy He Allawonny fables WCTILELY aia COAG HL ann amen the fi Table ic riviny ewe | Aatniosine | stadium | ntipnntan PreeNoney | Sebati WOOL P Relay 1d Pte Annoy lo Hino Wana 1002 1thaty runs flan Arnon Ww 1000 Dac Le fupor Power a oo VsFolig 108 [Lang juny tar Annoy a 000 OL fang WHE Discus Tw fHaper Powvor 0 m0 19-Mav a Table COACH Peoue Name | Acode | 1 Alnvad Huonsain 7) a Ravinder 00H ’ Janita 1001 4 Nana 1003 Eve the output of the following SOL, querien () SELECT COUNT. (DISTINCT. PartlelpantoNum) PROM ACTIVITY ; (i) SELECT. MAX(ScheduleDate), MIN(HeheduleDate) HROM ACTIVITY ; (ii) SELUCT Name, ActivilyNamw ROM ACTIVITY A, COACH @ WHERE A.Acode = C.Acode AND APartlelpantaNum = Wy (iv) SELECT DISTINGE PartlclpantsNum £'ROM ACTIVITY ; Ana, Os (ii) MAX(Schedulevate) MIN(Scheduledate) 19-Mar-04 12-Daceos (i) Name ACTIVITYNAME Navinder Discuss throw (io) 16 10 a Scanned with CamScanner a | UII DATA MANAGEMENT (601, Diango) 221 yo followins tables GAMES and PLAYER and answer the follown arts of ttt [CBSE Sample Paper Il, 121 Table : GAMES. ~~ GameName Type _| Number | PrizeMoney | ScheduleDate arom Board Indoor 2 5000 23-Jan-2004 Badminton Outdoor 2 12000 12-Dec-2003 e ‘Table Tennis Indoor 4 8000 14-Feb-2004 Chess Indoor 2 9000 01-Jan-2004 Lawn Tennis | Outdoor | 4 225000 19-Mar-2004 Table : PLAYER | _ Pode Name ode 1 Nabi Ahmad] 101 2 Ravi Sahai 108 3 Jatin 101 4 Nazneen 103 i thr ott of the following SQL queries: (y SELECT COUNT (DISTINCT Number) FROM GAMES ; (i) SELECT MAX(ScheduleDate), MIN(ScheduleDate) FROM GAMES ; (ii) SELECT Name, GameName FROM GAMES G, PLAYER P WHERE G.GCode = P.GCode AND GPrizeMoney > 10000 ; (jo) SELECT DISTINCT GCode FROM PLAYER ; Ans. (2 (i) Max(ScheduleDate) MIN(ScheduleDate) 19-Mar-2004 12-Dec-2003 (ii) Ravi Sahai Lawn Tennis (iv) ms YouTube :Notion Tube 174, Consider the following tables CABHUB and CUSTOMER and ansiver te following parts of this question ICBSE D 12] Table : CABHUB Veode | VehicleName Make Color: Capacity, Charges 100 Innova Toyota WHITE 7 15 1 SX4 Suzuki BLUE 4 4 | 104 C Class Mercedes | RED 4 35 Li AStar Suzuki | WHITE 3 4 x Indigo Tata SILVER 3 2 Scanned with CamScanner y 24) yye FAN WHE OAMIYIEN ONCE dst Vali cos tone ioe ie | ia ' Henan sa 0 ; fe a rm ' Peasy Shae tue ' oto Dal “4 Cie He dat thn pollonisny, SOL quer (REECE CLINE (DISTINGE Make) PROMO AHHH, (1) SELECT MANE tinios), MINE hanes) PRORE CATHIE, HH) BEL RCT COUNTC), Make bite IM CARTIER 1H) BEL HCT Velie taNanw PRON © ABETUD AVE Capea Au “oa Wi) 48 wv Gil) Tnva Lid query (iu) 8X4 Chass 175 Consider the following tablea CARDEN and CUSTOMER did auewer the pallowing pits of thes question Hen aE OD 1) Table CARIN | bode. CulNane Make Cola Capacity Che ony A sitar uy | Nt) \ " 50 Indign Fata sILVEH ‘ Ww we linevea Voyola WHEE ¥ Wo oe aNd ful | Snr ‘ " ay © Clase Meredes ep ' 4 Pable s CUS TON tlode ‘none feode 00 Hemant Gali any 7) Haj Lal fu hy Horner Ohl uli 1d Ketan Dal Aa Choe the ondynel of the follovviny SOL queries () SELRCT COURT (DISTINGT Makey HOM CARER j OH) SELECT MAX(Charyes), MIN Haryea) HOM CARTER; () SELBOT COUNT), Make PMLA CAML EAL; (uy SELECT Cortana PHO CANNEL YEH Cnpoeity Ay - ~~ Scanned with CamScanner UNIT: DATA MANAGEMENT (SaL, Dong) 223. ans ot 2 wo ® nvatid wery sya @) Ceaass so te flowin, ales WORKER and PAYLEVEL and answoer the following parts of ye one [CBSE D 11] ws Table : WORKER ie NAME esiG | PLEVEL 07 008 Tr | Ratthe Shyam Supervisor | POo1 | 13-Sep-2004 | 23-Aug-1961 ip | Chander Nath | Operator poo3 | 22-Feb-2010 | 12-Jul-1987 B Fizza Operator 003 14-Jun-2009 14-Oct-1983 15 | Ameen ‘Ahmed | Mechanic poor | 21-Aug-2006 | 13-Mar-1984 is | Sanya Clerk poo2 | 19-Dec-2005 | 09-Jun-1983. Table : PAYLEVEL LEVEL PAY. ‘ALLOWANCE POOL 26000 12000 P002 22000 10000 ‘PO03 12000 6000 Give the output of the following SQL queries + (i) SELECT COUNT (PLEVEL), PLEVEL FI (i SELECT MAX(DOB), MIN(DO)) FROM WORKER ; (ii) SELECT Name, Pay FROM WORKER W, PAYLEVEL P WHERE WPLEVEL = P-PLEVEL AND W.ECODE < 13 ; ROM WORKER GROUP BY PLEVEL ; (io) SELECT PLEVEL, PAY + ALLOWANCE FROM PAYLEVEL WHERE PLEVEL = "PO0S ; Ans, Oa Pee 2 Pees, 2 Pee (i) 12-3ul-1987 13-Sep-2004 (ii) Name i. Radhe Shyam 26000 Chander Nath 12000 (i) pe03 18000 be Scanned with CamScanner 224 MOVE Fast wd COMPUTER SCIE 177. Constdler the rae ] So CODE WAME | DESIG | SGRADE | le 101 | Abdul Ahmad _| EXECUTIVE | $03 | 23-Mar-2003 | 13tent99) 102 | Ravi Chander | HEAD-IT | S02 | 12-Feb-2010 | 2 Jur 1967 103} John Ken RECEPTIONIST | $03 | 2¢Jun-2009 | 2+ Feb1905 105 | Nazar Ameen | GM 108 | PriyamSen | CEO S02 | 11-Aug-2006 | 03-Mar-1994 ‘S01 22-Dec-2004 | 19}an-1959 Table : SALGRADE [7 see sare] SOL 56000 18000 soa 2000 12000 S03 24000 8000 | Give the output of the following SQL queries () SELECT COUNT (SGRADE), SGRADE FROM EMPLOYEE GROUP BY SGRADE; i) SELECT MIN(DOB), MAX(DO)) FROM EMPLOYEE ; (ii) SELECT NAME, SALARY FROM EMPLOYEE E, SALGRADE S WHERE ESGRADE = SSGRADE AND E.ECODE < 103 ; (iv) SELECT SGRADE, SALARY +HRA FROM SALGRADE WHERE SGRADE = “Mz; Ans. (COUNT scrape 2 $03 2 sez 1 sei ()13-3an-1980 12-Feb-2010 ii) NaMe SALARY AbdulAhmad 24000 Ravi Chander 32000 (iv) scrape SALARY + HRA, sez 44000 Scanned with CamScanner UNIT DATA MANAGEMENE 01, Djangay 225; r 5 nate the following tables STORE aaud SUPPLIERS wid answer the folowing, parts of this jon ICHSE D 401 vt au Vable : STORE, Item Scola | ary stemNo fs tasty | 08 ‘Sharpener Clam 2” wo * | 3bfunce awa Gel Pow Ut 21 150 12 | aebeo za Gal Vt Cla a | ao | a [raters | 20 Hraner Small R 20 6 W4an | 20 Keawer Dip, 2 02-Dec-09 Fable : SUPPLIERS Sname Premium Stationers Soft Plastics ply the output of the following SQL queries : 4 ICT COUNT (DISTINCT Scode) FROM Store ; (ii) SI “T Rate * Qty FROM Store WHERE ItemNo = 2004 ; (ii) SELECT Item, Sname PROM Store §, Suppliers P Scode = P,Scode AND ItemNo = 2006 ; (in) MAX (LastBuy) FROM Store ; Ans. 3 (ii) 880 (iff) GelPenClassic Premium Stationers (iv) 24-Feb-10 179. Consider the following tablex STOCK and DEALERS and answer the following parts of this question : ICBSE OD 101 Table : STOCK — . a __., ttento_| Item, Dcode Qty _|_UnitPrice | stockoate 5005 Ball Pen 0.5 102 100 16 ‘eMar-10 5003, Ball Pen 0.25 102 150 20 Ol-fan-10 502, Gel Pen Premium 101 125 W 14-Feb-10 | 5006 Gel Pen Clavie lol 200 22 | 01-Jan-09 5001 Eraver Small 102, 210 5 19-Mar-09 5004 Eraser Big, |_ 5009 _|_ Sharpener Classic os Scanned with CamScanner SELECT COUNT(DISTINCT Deode) FROM Stock SELECT Qty * UnitPrice FROM Stock WHERE ItemNo = 5006 ; (#) SELECT Item, Dname FROM Stock S, Dealers D WHERE S.Deade = D_Deode AND ItemNo = 5005 ; () SELECT MIN(StockDate) FROM Stock ; Ans. @ 3 ii) Eraser Big Clear Deals (=) @1-Jan-e9 per given Ios px Table : GARMENT Soe Price FOE __|_-REAOAE 10023 PENCIL SKIRT 150 RS ISDECES 10001 FORMAL SHIRT po | FR | yANGS roo2 INFORMAL SHIRT 5 P| SUNS 10024 BABY TOP mo FB 100890 ToursxiRT |S) 10019 EVENING GOWN | so | RS | 10009 | INFORMAL PANT — 100 Foz | 2eocT4s 10017 FORMAL PANT 1350 FOL OS MARES wooo | FROCK | so) | COSSEPME 10s?) SLACKS. = RE | SLOCTHS Table : FABRIC Fo POLYSTER | Re COTTON | RS SILK FOL |_TERELENE (@ SELECT SUM (PRICE) FROM GARMENT WHERE FCODE = ‘FOU ; OO - Scanned with CamScanner Nit IIL DATA MANAGEMENT (SQL, Diongo) = 227 _—__——— ECT DESCRIPTION, TYPE FROM GARMENT, FABRIC GARMENT.FCODE = FABRIC.FCODE AND GARMENT.PRICE >= 1260 ; (aiy SELECT MAX (FCODE) FROM FABRIC ; (jo) SELECT COUNT (DISTINCT PRICE) FROM GARMENT ; My ammo YouTube :Notion Tube (i) description Type INFORMAL SHIRT COTTON INFORMAL PANT coTTON FORMAL PANT TERELENE iii) MAX(FCODE) Fo4 (io) COUNT(DISTINCT PRICE) 7 tsi. Gite output for following SQL queries as per given tablets): [CBSE OD 09} Table : DRESS pcove DESCRIPTION PRICE McODE _| _LAUNCHDATE | ro0ot FORMAL SHIRT 1250 ‘MOO DANS | 0020 FROCK 750 Moot | 09-SEP-07 | 10012 INFORMAL SHIRT 1450 Moor | o6JUN-08 10019 EVENING GOWN 850 M003 06-JUN-08 | | 10090 TULIP SKIRT 850 Mooz (| 31-MARO7 | | 10023 PENCIL SKIRT 1250 Moos | 19.06C08 | | 10089 SLACKS, 850 Moos = |200cr03 | 10007 FORMAL PANT 1450 ool OO-MAROS | 10009 INFORMAL PANT 1400 ‘M002 mwocTs | 10024 BABY TOP 650 M003 O7-APRO7 | Table : MATERIAL, MCODE Moo1 TERELENE ‘M002 COTTON Moos POLYESTER M003 SILK (i) SELECT SUM (PRICE) FROM DRESS WHERE MCODE = ‘M001’ ; (ii) SELECT DESCRIPTION, TYPE FROM DRESS, MATERIAL WHERE DRESS.MCODE = MATERIAL.MCODE AND DRESS.PRICE >= 1250 ; Scanned with CamScanner 228 MOVE FAST WITH COMPUTER SCIENCE (Python) - Xi (iii), SELECT MAX(MCODE) FROM MATERIAL ; (iv) SELECT COUNT(DISTINCT PRICE) FROM DRESS ; Ans. (i) SUM(PRICE) 2700 (ii) Description Type FORMAL SHIRT TERELENE INFORMAL SHIRT COTTON PENCIL SKIRT SILK | FORMAL PANT TERELENE INFORMAL PANT COTTON (iif) max(MCODE) moos (iv) COUNT(DISTINCT PRICE) 6 182. Give output for following SQL queries as per given table(s) : [CBSE D og Table : PRODUCT PID ProductName Manufacturer Price TPO1 Talcom Powder LAK 40 FWo5 Face Wash ABC 45 BSO1 Bath Soap ABC 55 SHO6 Shampoo XYZ 120 FW12 Face Wash XYZ 95 Table : CLIENT CID ClientName City PID 1 Cosmetic Shop Delhi FWO5 06 Total Health Mumbai BSOL 2 Live Life Delhi SHO6 8 Pretty Woman Delhi FWI2 16 Dreams Banglore ra | () SELECT DISTINCT City FROM Client ; (i) SELECT Manufacturer, MAX(Price), Min(Price), Count(*)" FROM Product GROUP BY Manufacturer ; (iii) SELECT ClientName, ProductName FROM Product, Client WHERE Client.P_Id = Product.P_Id ; SELECT ProductName, Price * 4 FROM Product ; Scanned with CamScanner Ans. @) (ii) (iii) (iv) Delhi Mumbai Banglore Un ABC gs vz 120 ClientName Cosmetic shop Total Health Live Life Pretty woman Dreams, Talcom Powder Face Wash Bath Sodp Shampoo. Face Wash 40 45 95, Manufacturer Be ABC xyz xz Lak 169 180 220 480 380 183. Give output for following SQL queries as er given table(s) : ‘Table : ITEM Lio ItemName Manufacturer Price PCoL Personal Computer| ABC 35000 Leos Laptop ABC 55000 Pcos Personal Computer| xyz 32000 P06 Personal Computer| COMP 37000 Los Laptop POR hd Table : CUSTOMER os C0 Customertiame Sy ses eae u a N Roy Delhi oe) i ros 06 H Singh Mumbai : Delhi a 2 R Pandey Dethi 1s 15 C Sharma glore rou 16 K Agarwal Bang! (i) SELECT DISTINCT City FROM Customer ; (ii) SELECT ItemName, MAX(Price), Count(*) FROM Item GROUP BY ItemName ; [CBSE OD os} Scanned with CamScanner 230 MOVE FAST WITH COMPUTER SCIENCE (Python) ~ Xil (iti) SELECT CustomerName, Manufacturer FROM Item, C ustomer WHERE Item.|_ID = Customer._ID ; (iv) SELECT ItemName, Price * 100 ON FROM Item WHERE Manufacturer = ‘ABC’ ; Ans. (i) Delhi Mumbai Bangalore (ii) Personal Computer 37000 3 Laptop 57000 2 (iii) NRoy POR HSingh xz R Pandey comp Sharma POR K Agarwal ABC (iv) Personalcomputer 3500000 Laptop 5500000 184. Give output for following SQL queries as per given table(s) : ICBSE D or Table : SENDER SenderID SenderName SenderAddress ‘Sendertiy |) NDOL R Jain 2, ABC Appts New Delhi Muo2 H Sinha 12, Newtown Mumbai MUI5 $ Jha 27/8, Park Street Mumbai ND50 T Prasad 122-K, SDA New Delhi Table : RECIPIENT |_ Recto | Senderto RecName Rechddress Recity Koos | NDOI R Bajpayee 5, Central Avenue Kolkata NDos | Muo2 $ Mahajan 116, A Vibar New Delhi Mui9_ | NDoI H Singh 2A, Andheri East Mumbai Mus2_ | MuIs PK Swamy | B5, CS Terminus Mumbai NDss__ | ND50 S$ Tripathi 13, BID, Mayur Vihar | New Delhi (i) SELECT DISTINCT SenderCity FROM Sender ; (ii) SELECT A.SenderName, B.RecName FROM Sender A, Recipient B WHERE A.SenderID = B.SenderID AND B.RecCity = ‘Mumbai’ ; _aadl Scanned with CamScanner 230 \ A MANAGEMENT (SQL, Django] (iil) SELECT RecName, Re FROM Recipient WHERE RecCity NOT IN(Mumbai’, ‘Kolkata’) : SELECT RecID, RecName FROM Recipient WHERE SenderID = ‘MU02’ OR (iv) nderID = ‘NDSO" ; Ans. (i) NewDelhi Mumbai (i) Rain HSingh saha PK Swamy (iii) SMahajan 116, AVihar s Tripathi 13, 81D, Mayur Vihar (iv) NOOB smahajan No4s s Tripathi 185, Give output for following SQL queries as per given tablets) ICHSE OD 07] ‘Table : CONSIGNOR | Cnortd CnorNome | __CnorAddress_—|__City | R Singhal 24, ABC Enclave New Delhi | NDo2 | Amit Kumar | 123, Palm Avenue | New Delhi MuIs | R Kohli SIA, South Street Mumbai MUS50 | S Kaur 27-K, Westend | | | Table : CONSIGNEE | Gam [coro | eetome | __coeeadtess | Greatly muos | NDO1 | Rahul Kishore | 5, Park Avenue | Mumbai pos | Noo | PDhingra | 169, Moore Enclave | New Delhi Kos | MUIS | AP Roy o”DThLDTr Ll Mu32 | ND02 |S Mittal P 245, AB Colony | Mumbai Nps |Muso | BP Jain 13, Block D, A Vihar | New Dethi_ () SELECT DISTINCT City FROM CONSIGNEE ; (ii) SELECT A.CnorName, B.CneeName FROM Consignor A, Consignee B WHERE A.CnorlD = B.CnorlD AND B.CneeCit (iii) SELECT CneeName, CneeAddress FROM Consignee WHERE CneeCity NOT IN(’Mumbai’, ‘Kolkata’) ; *Mumbai’ ; Scanned with CamScanner 232 MOVE FAST WIM COMPUTER SCIENCE (Pye) ~ Xi FROM Consignee WHERE CnorlD = “MULS’ OR CnorlD =“NDOV' ; Ans. (0) There no column by the name City in the table CONSIGNEE, Hoye, change the column from City to CneeCity, the query results ay +" iy Cneecity Mumbai New Delhi kolkata (ii) R Singhal Rahul Kishore Amit Kumar smittal (iii) PDhingra 16/3, Moore Enclave 8P Jain 13, Block D, AVihar (iv) mues Rahul Kishore Ko19 AP Roy 186. Give output for following queries as per given table(s) : CBSE D wy Table : DOCTOR NAME DEPT SEX_|_ EXPERIENCE 101 | John ENT M 2 104 | Smith ORTHOPEDIC M 5 107 | George CARDIOLOGY M 10 14 | Lara SKIN F 3 109 | K George MEDICINE F 9 105 | Johnson ORTHOPEDIC M 10 117 | Lucy ENT F 3 m1 | Bill MEDICINE F 2 130 | Morphy ORTHOPEDIC M 15 Table : SALARY Jo. BASIC ‘Auowance | __CONSULTATION _ 101 12000 1000 300 104 23000 2300 500 107 32000 4000 500 1s 12000 5200 100 109 42000 1700 200 105 18900 1690 300 130 21700 2600 300 Scanned with CamScanner ad SCOT UNIT IT: DATA MANAGEMENT {SQL Django) 233 ' NAME, DEPT, BASIC FROM DOCTOR, SALARY NT” AND DOCTOR.ID = SALARYAID ; Ans a4 pane DEPT BASIC ai gonn ENT 12000 output for following SQL queries as per given table(s) : ICBSE OD 06] sie Table : FLIGHTS “FLNO. STARTING ENDING o_puicnrs | No_sT0Ps_| 1C301 MUMBAI DELHI 8 | 0 | ios BANGALORE | DELHI 2 ea meio | INDORE MUMBAI 3 0 ic | DELHT MUMBAL 8 0 | ‘amsi2._| KANPUR BANGALORE 3 1 1¢899 MUMBAI KOCHI 1 4 awsot | DELHI ‘TRIVANDRUM 1 5 uis9 | MUMBAI MADRAS 3 3 ic71__| DELHI AHMEDABAD 4 o | Table : FARES FLNO. AIRLINES FARE TAX 1C701 Indian Airlines 6500 10 Mu499 Sahara 9400 5 ‘AMSO1L Jet Airways 13450 8 1c899 Indian Airlines 8300 4 Ic302 Indian Airlines 4300 10 1c799 Indian Airlines 10500 10 Mcio1 Decean Airlines 3500 4 () SELECT FL_NO, NO_FLIGHTS, AIRLINES from FLIGHTS, FARES where STARTING = “DELHI” AND FLIGHTS.FL_NO = FARES.FL_NO. (i) SELECT count(distinct ENDING) from FLIGHTS. Ans, (i) There is an error in the query as FL_NO field is present in both the tables we Tequire to qualify the column name by its table name. Assuming the FLLNO field is qualified as FLIGHTS.FL_NO or FARES.FL_NO the output will be : FL_NO NO_FLIGHTS AIRLINES AMSO1 1 Jet Airways 1c3@2 8 Indian Airlines K7@7 4 Indian Airlines (i) 7 Be Scanned with CamScanner 234 MOVE FAST Wi COMPUTER SCIENCE [Pynon] — Xi 188, ine output for following SQL queries as per given table(s) Table : EMPLOYEES |__Empip | _FIRSTNAME __LASTNAME. ADDRESS o10 = Smith 83 First Street | Howard | ws | Mary | Jones | 842 vine Ave, | Losantivitle 152 | Sam Tones | 33 Elm St. | Pacis | cee acermn—|wousi0 —ltpen | | 300 Robert | Samuel | 9 Fifth Cross Washington | 335 Henry Williams 12 Moore Street | Boston | 400 Rachel | Lee 121 Harrison St. New York mi [Thompson | 11 Red Road Paris, i i Eee Ps | Table : EMPSALARY [ ‘EMPID ‘SALARY | BENEFITS | DESIGNATION | 105 | 65000 | 15000 | Manager | as) 000 | as | ietor Jam | tm frome | 244 | 50000 | 12000 ‘Clerk | soo wo | i fom | - ow | om lon £ | rm amo | om [sae | [mo fat | | 441 28000 (i) SELECT FIRSTNAME, SALARY FROM EMPLOYEES, EMPSALARY WHERE DESIGNATION = ‘Salesman’ AND EMPLOYEES.EMPID = EMPSALARY.EMPID ; (ii) SELECT COUNT(DISTINCT DESIGNATION) FROM EMPSALARY ; (iii) SELECT DESIGNATION, SUM(SALARY) FROM EMPSALARY GROUP BY DESIGNATION HAVING COUNT(*) > 2; (iv) SELECT SUM(BEI FROM EMPLOYEES WHERE DESIGNATION = ‘Clerk’ ; Scanned with CamScanner Ans. () Rachel 32000 Peter 28000 a 4 (ii) Manager = 215000 clerk 135000 (i) 32000 ¢ output for followi SQL queries as pe en tablets) + : [CBSE OD os} Table : WORKERS Tv __| renin | ine | en al 102 | Sam | Tones | 33 Elm St. Paris | | 105 Sarah | Ackerman | Hus. 10 New York | | 4 Manila Sengupta, 24 Friends Street | New Delhi | no George Smith SOFint Steet | Howand | 255 Mary Jones S12 Vine Ave. | Losantiville 300 Robert Samuel 9 Fifth Cross | Washington 335 Henry Williams | 12 Moore Street | Boston. | 403 | Ronny Lee 121 Harrison St. | New York | 451 Pat Thompson | 11 Red Road Paris Table : DESIG [7 swaer | eeners | oes 75000 85000 70000 | eenerrts | oesicwarzow | 15000 | Manager| 25000 15000 12500 12000 Director Manager Manager Clerk Clerk Clerk 10000 Salesman (i) SELECT FIRSTNAME, SALARY FROM WORKERS, DESIG WHERE DESIGNATION = ‘Manager’ AND EMPLOYEE.W_ID = DESIG.W.ID ; (ii) SELECT COUNT(DISTINCT DESIGNATION) FROM DESIG ; Scanned with CamScanner 236 MOVE FAST WII COMPUTER SCIENCE (Python) DESIGNATION, SUM(SALARY) it) 2M DE 3ROUP BY DESIGNATION HAVING COUNT(*) < 3; P SUM(BENEFITS) ROM WORKERS WHERE DESIGNATION = ‘Salesman’ ; Ans. (Sam 75000 Manila 7000 | George 75600 (i) 4 (iii) Director 85000 Salesman 60000 (&) Error in question ~ there are no Benefits and Designation columns in tay WORKERS. If we assume and change the table as DESIG for this query, outpy will be 15000, 190. Give output for following SQL queries as per given table(s) : (CBSE D oy Table : Books | Book.td | Book Name Author_Name | Publishers | Price | Type | ay. | eooor | Fast Cook Lata Kapoor EPB 355 | Cookery [5 [rat | the teas [ovmam roptie [rat pos | eso free [a Brian and Brooke | EPB 350 [tex — | 10 [ror | ris coe | T0002 | C++ Brainworks | A.W. Rossaine FO002 Thunderbolts Anna Roberts TDH 350 | Text 15 First Publ. | _750_| Fiction _| 50 Table : Issued Quantity Issued (i) SELECT COUNT(*) FROM Books ; (ii) SELECT MAX(Price) FROM Books WHERE Quantity >= 15 ; (iii) SELECT Book_Name, Author_Name FROM Books WHERE Publishers = “EPB"i (i) SELECT COUNT (DISTINCT Publishers) FROM Books WHERE Price >= 400 Ans. @ 5 (i) 750 (ili) Fast Cook Lata Kapoor My First C++ Brian and Brooke (iv) 1 A ad Scanned with CamScanner ESE SS ur INIT IIL: DATA MANAGEMENT (SQL, OJango} 237 1 tablet): [CBSE OD os) Table : Books Author-Name | Publisher | Price i William Hopkins | First publ. | 750 is Thunderbolts | Anna Roberts | Fist Publ. | 700 5 My first C++ | Brian and Brooke | EPB 250 a C#+ Brainworks | A.W. Rossaine | TDH 325. | Text 5 Fast cook Lata Kapoor Ero m0. || cookery, 8 Table : Issued Book_Id Quantity_Issued FOOOL TOOL C0001 () SELECT COUNT(DISTINCT Publishers) FROM Books. (i) SELECT SUM(Price) FROM Books WHERE Quantity > 5 (ii) SELECT Book Name, Author_Name FROM Books WHERE Price < 500. (jo) SELECT COUNT (").FROM Books. Ans. ' @ 3 (i) 1350 (iii) My first CH Brian and Brooke C++ Brainworks A.W. Rossaine Fast cook Lata Kapoor (e) 5 192. Give output for following SQL queries as per given table : [CBSE D 031 ‘ Table : FURNITURE [ NO. ITEMNAME | TYPE. DATEOFSTOCK | PRICE 4 White lotus Double Bed 23/02/02 30000 2. |. Pink feather Baby cot 20/01/02 7000 3, | Dolphin Baby cot, | 19/02/02 9500 4 Decent Office Table 01/01/02 25000 5. Comfort zone Double Bed 12/01/02 25000 6. | Donald Baby cot 24/02/02 6500 7. | Royal Finish Office Table 20/02/02 18000 8 | Royal tiger Sofa 2202/02 | 31000 9. Econo sitting, Sofa 13/12/01 9500 10. | Eating Paradise | Dining Table | _19/02/02_| 11500 Scanned with CamScanner ECU HIN EMO HIM HURT BE APO PAPAS OLD PRONE EVHITOUHE 220 AWE OUND ERATE URSTLURE WEEE POPE gly ge CSSA UAGIC FROME FURNITURE WHE DA TORSITg p 0) Ae wos wore wan rome) 19 Give ewtput for following SQL queries as por given tablets) WHE Ct gj Table tN Hons wo innnae | Wee oareorsroce | pasce | orscoumy J 1 | Red rose Hnble ted 24940 oe th 2 St tony Baby vot } DOVE uy Ww 1] Jery’s home | Baby cot wom | eon w 4 | Rough wood | Offive table | oOLO2 aun aw ‘ Comfort zone | Dyvubte theat | A240 aw 6 | ery took tabysot | aon w 7. | Lion king Ovtiee Table | 2yen402 | toc 0 * Royal tiger tata PWIND Sup ” 5% | Park siting js tain a 6 0 ine Paradise | Dining Table | svoae2 | hom In (SELECT COUNTOMISTINCT TYPE) FROM INTERIORS ; (i) SELECT AVG(MSCOUNT) PROM INTERIORS WHERE TYME = “Dahiy cut”; (Ui) SELECT SUM(PRICH) FROM INTERIORS WHERE DATHOPSIOCK< (2ARA0 Ans, Os a) (iit) 53000 fennt pal 196 Give output for following SQL queries as per given table Vable Lat : | Renvane | onrctton 1 | Computer | eo | 2 Printer: | 1000, {L% _ [scammer | twa Scanned with CamScanner

You might also like