Page 2 :
as, ha, n, , Strictly according to the latest reduced & bifurcated syllabus and the latest sample Question, Paper released by the central Board of secondary education, New Delhi,, for the Term I Examination to be held in november-december 2021., , QUESTION BANK and, CBSE Sample Paper with, , Pr, ak, , Model Test Papers in, , Computer Science, , Including Projects (Binary files and CSV files), , ot, , he, , rs, , [subject code : 083], , For CLASS, , 12, , Term-I, EXAMINATION, , By, , As per the latest reduced &, November-December 2021., , MCA, MSC (IT), , bifurcated syllabus for term i examination to be held in, , al, , , , Br, , Gurmeet Singh, , Chapterwise Multiple choice Questions., , , , The latest cBse sample Question Paper for term i examination to be held in November-December 2021., , oy, , , , 5 Model test Papers based on the latest CBSE Sample Question Paper for Term I Examination., , G, , , , GOYAL BROTHERS PRAKASHAN
Page 3 : Goyal Brothers Prakashan, Educational, , Publishers, , Administrative Office :, D-231, Sector 63, Noida-201301 (U.P.), Phone : 0120-4655555, , as, ha, n, , Sales & Registered Office :, 11/1903, Chuna Mandi, Paharganj, New Delhi - 110055, Post Box : 5720, Phones : 43551877 & 43561877, E-mail :
[email protected], Website : www.goyal-books.com, , Showrooms :, Ahmedabad : Y-10, Dev Castle Complex Opp. Radhekrishan Villa, Jaymala-Govindwadi Road, Isanpur, Ahmedabad–382443 (Gujarat) Tel : 09925004030, , Pr, ak, , : No. 50/39 Ground Floor, Five Furlong Road Guindy, Chennai–600 032, Chennai, (Tamil Nadu) Tel : 044-22552776, Fax : 044-22552767, , Guwahati : Plot No. 1179, KRB Road, Bharalumukh, near Post Office, Railway Gate No.8, Guwahati – 781001 (Assam), Phone : 0361-2735337, Hyderabad : F-7/8/41, First Floor, Agarwal Chambers, 5-9-1121, King Kothi Road,, Hyderabad - 500001 Tele-fax : 23211332, Kochi, : Fair Heavens, H.No. 52-2783/A, Shine Road, Vytilla, Emakulam - 682019 (Kerala) Phone : 0484-2305288, , rs, , Kolkata, : No. 203, 2nd Floor, Fomra Towers, 84-A, Acharya Jagdish Chandra Bose Road,, Kolkata - 700014 Phone : 033-22262683, , he, , Bengaluru : 1681/5/4, Ground Floor, 3rd Main Ramamohanapuram,, Bengaluru - 560 021, Phone : 080-23320655, , ot, , Bhopal, : Plot No. 203, Zone-II, M.P. Nagar, Bhopal-462 011 (M.P.),, , Tele-fax : 0755-4271371, : B-318, Sector-B, Mahanagar, Opposite P.A.C Main Gate,, Lucknow, , Br, , Lucknow - 226 006, Phone : 0522-2320841, Patna, : Ravi Kiran Apartment, Flat No. 2-A, Second floor,, Near Water Pumping Station, Pani Tanki Lane, Pirmohani, Patna – 800003, Nagpur, : Thakkar Villa, House No. 436 Joshiwadi, Sibuldi, Nagpur – 440012, , Phone : 9823655077, , G, , oy, , al, , To buy our books and e-books online log on to www.goyal-books.com, © Reserved, Edition : 2021, Price : ` 230, , Disclaimer, • All the brand, product names and logo referred to in this book are hereby acknowledged to be the trademarks of, their respective organisations. We are not associated with any product or vendor mentioned in this book., • Due care and diligence has been taken while writing, editing and printing the book. Neither the, author nor the publishers of the book hold any responsibility for any mistakes that may have inadvertently crept in., , Published & Printed by, Roshan Lal Goyal for Goyal Brothers Prakashan, New Delhi
Page 4 :
as, ha, n, , Preface, We are pleased to present our book SCORE PLUS Question Bank and CBSE Sample Paper with, Model Test Papers in Computer Science for Class XII (Subject Code 083) in strict accordance, with the Latest Reduced of bifurcated Syllabus and the Latest Sample Question Paper released, by the Central Board of Secondary Education, New Delhi, for Term I Examination to be held in, November-December 2021., , Pr, ak, , This book contains the brief introduction of each topic with solved examples. In each chapter,, topicwise questions have been set. “Easy to difficult” level of questions is maintained. We have, tried to clear all the concepts in easy language and with solved examples. Most of the questions, are taken from the last year CBSE paper or based on CBSE pattern., In the next part of book, sample question paper of Computer Science released by CBSE with, its solution is published. After sample paper, there are 5 model test papers with their solutions, prepared keeping in mind the blueprint of the CBSE sample question paper., Some specific features of this book are:, , Strictly as per the latest Reduced and bifurcated syllabus and the latest CBSE Sample, Question Paper released by the CBSE for Term I Examination to be held in November, December 2021., , , , Chapterwise Question Bank provides topicwise comprehensive range of solved and, unsolved questions including questions from past years’ papers to provide thorough, understanding of the chapter., , , , The latest CBSE Sample Question Paper for Term I Examination to be held in NovemberDecember 2021., , , , 5 Model Test Papers based on the latest CBSE Sample Question Paper for Term I, Examination., , ot, , he, , rs, , , , G, , oy, , al, , Br, , We hope this book provides enough practice materials and would help students in scoring high, during this academic year along with the final board examination., Author
Page 5 :
Syllabus, , as, ha, n, , COMPUTER SCIENCE, CLASS-XII Code No. 083, 2021-22, 1. Prerequisites, Computer Science- Class XI, , (b) explain and use the concept of file handling., (c) use basic data structure: Stacks., (d) explain basics of computer networks., , Pr, ak, , 2. Learning Outcomes, Student should be able to, (a) apply the concept of function., , (e) use Database concepts, SQL along with connectivity between Python and SQL., 3. Distribution of Marks:, , Marks, , Theory, , Practical, , 40, , 50, , 25, , Computational Thinking and, Programming - 2, , II, , Computer Networks, , 10, , 10, , ---, , III, , Database Management, , 20, , 20, , 15, , 70, , 80, , 40, , ot, , he, , I, , Br, , Total, , oy, , al, , Unit No, , G, , Periods, , rs, , Unit Name, , Unit, No., , Unit Name, , Term-1, , Term-2, , I, , Computational, Thinking and, Programming - 2, , 35, , 5, , II, , Computer Networks, , ---, , 10, , III, , Database, Management, , ---, , 20, , 35, , 35, , Total
Page 6 :
4. Unit wise Syllabus, , TERM I, , as, ha, n, , Unit I: Computational Thinking and Programming – 2, • Revision of Python topics covered in Class XI., • Functions: types of function (built-in functions, functions defined in module, user defined functions),, creating user defined function, arguments and parameters, default parameters, positional parameters, function, returning value(s), flow of execution, scope of a variable (global scope, local scope), • Introduction to files, types of files (Text file, Binary file, CSV file), relative and absolute paths, , • Text file: opening a text file, text file open modes (r, r+, w, w+, a, a+), closing a text file, opening a file using, with clause, writing/appending data to a text file using write() and writelines(), reading from a text file using, read(), readline() and readlines(), seek and tell methods, manipulation of data in a text file, , Pr, ak, , • Binary file: basic operations on a binary file: open using file open modes (rb, rb+, wb, wb+, ab, ab+), close a binary, file, import pickle module, dump() and load() method, read, write/create, search, append and update operations, in a binary file, • CSV file: import csv module, open / close csv file, write into a csv file using csv.writerow() and read from a csv, file using csv.reader( ), Suggested Practical List: Term I, Python Programming, , • Read a text file line by line and display each word separated by a #., , rs, , • Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the file., • Remove all the lines that contain the character 'a' in a file and write it to another file., , he, , • Create a binary file with name and roll number. Search for a given roll number and display the name, if, not found display appropriate message., • Create a binary file with roll number, name and marks. Input a roll number and update the marks., , G, , oy, , al, , Br, , ot, , • Write a random number generator that generates random numbers between 1 and 6 (simulates a dice)., • Create a CSV file by entering user-id and password, read and search the password for given user- id.
Page 7 :
as, ha, n, , CONTENTS, , section a: chaPterWise Question Bank, 1. Revision Tour, , 1 – 42, , ... ... ..., , 43 – 66, , Pr, ak, , 2. Python Functions, , ... ... ..., , 3. File Handling, , ... ... ..., , 67 – 122, , section B: cBse saMPle Question PaPer, [Released by CBSE in September 2021, , CBSE Sample Question Paper, , ... ... ..., , 123 – 131, , he, , , , rs, , for the Term I Examination to be held in November-December 2021], , section c: Model test PaPers, , [Based on the latest CBSE Sample Question Paper, , ot, , for the Term I Examination to be held in November-December 2021], , Model Test Paper – 1, , ... ... ..., , 132 – 139, , , , Model Test Paper – 2, , ... ... ..., , 140 – 147, , , , Model Test Paper – 3, , ... ... ..., , 148 – 154, , , , Model Test Paper – 4, , ... ... ..., , 155 – 162, , , , Model Test Paper – 5, , ... ... ..., , 163 – 170, , G, , oy, , al, , Br, ,
Page 8 :
1, , SECTION : A, , as, ha, n, , Revision Tour, , 1. What is python?, , Ans. Python is an interpreted, high-level, general-purpose programming language, which was created by Guido van, Rossum. It was first released in 1991. It is used in many applications like Software Development, Web Development,, System Scripting, Mathematics, etc., , Pr, ak, , features of Python, •, , Easy to use: due to simple syntax, it is very easy to implement., , •, , Interpreted Language: In python, every code is executed line by line., , •, , Cross-platform Language: can run on any platform Windows, Linux, Macintosh, Raspberry Pi, etc., , •, , Expressive Language: It supports a wide range of library., , •, , Free & Open Source: It can be downloaded free of cost., , disadvantages, , Lesser Libraries: As compared to other programming languages like c++, java, .Net, etc. it has a lesser number, of libraries., , •, , Slow Language: Being an interpreted language, the code is executed slowly., , •, , Weak on Type-Binding: A variable that is initially declared int can be changed to string at any point in the, program without any typecasting., , he, , rs, , •, , Br, , n=10, , ot, , 2. What is variable?, Ans. A variable is a named location used to store data in the memory. For example, in the following statement a, variable ‘n’ is created and assigned the value 10 to n., 3. How can multiple values be assigned to multiple variables and same value to different variables., Ans. Assigning multiple values to multiple variables:, a,b,c=10,20,”hello”, , al, , Assign the same value to multiple variables at once:, , x=y=z=50, , oy, , 4. Write code to create a variable num and assign 100 value to num., , Ans. num=100, , 1. tOKens, , G, , 5. Define token in python., Ans. Token: The smallest individual unit in a program is known as a token. There are five types of tokens allowed, in Python. They are :, • Keywords, • Identifiers, • Literals, • Operators, • Punctuators, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 1
Page 9 :
(i) Keywords, Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other, identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive., class, , from, , or, , None, , continue, , global, , pass, , True, , def, , if, , and, , del, , import, , as, , elif, , in, , assert, , else, , is, , async, , except, , lambda, , await, , finally, , nonlocal, , break, , for, , not, , as, ha, n, , False, , raise, , return, try, , while, with, , Pr, ak, , yield, , (ii) Identifier, , An identifier is a name given to entities like class, functions, variables etc., Rules for writing identifiers, , Identifier must always start with either a letter or an underscore (_). For example: _str, str, num, _num are all, valid name for the variables., , •, , Identifiers cannot start with a number. For example, 9num is not a valid variable name., , •, , The identifier cannot have special characters such as %, $, #.- etc, they can only have alphanumeric characters, and underscore (A to Z, a to z, 0-9 or _ )., , •, , An identifier cannot contain space., , •, , Identifier is case sensitive in Python which means num and NUM are two different variables in python., , •, , Keywords cannot be used as identifier., , he, , rs, , •, , Br, , ot, , 6. Out of the following, find those identifiers, which cannot be used for naming Variable or Functions in a Python, program:, 2 [OD 16], Total*Tax, While, class, switch, 3rdRow, finally, Column31, _Total, Ans. Total*Tax, class, 3rdRow, finally, 7. Identify invalid variable names out of the following. State reason if invalid., (i) for, (ii) –salary, (iii) salary12, Ans. Invalid variable names : (i) for and (ii) -salary, , [OD 16], , (iv) product, , al, , Reason : (i) ‘for’ : is a keyword, (ii) ‘-salary’ : variable name cannot start with special character., , oy, , 8. Identify invalid variable name(s) out of the following. State reason if invalid, , (i) While, Ans. (ii) 123salary, , (ii) 123salary, , (iii) Big, , [comptt 16], , (iv) Product, , G, , 9. Help Manish in identifying the incorrect variable name with justification from the following:, , (i) unit@price, (ii) fee, (iii) userid, (iv) avg marks , Ans. (i) unit@price; // Special symbols like „@‟ is not allowed in variable name, (iv) avg marks;// Spaces are not allowed in variable name, 2, , [SP 18], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 10 :
10. Identify the invalid variable names. State the reason if invalid., (i) Marks Unit, (ii) Product_1, (iii) Sales123, Ans. Invalid variable names are :, (i) Marks Unit, Reason : Variable Name should not contain space, (iv) 2Marks, Reason : Variable Name should not start with digit, , (iv) 2Marks, , , , as, ha, n, , , , , , , 1 [2018], , 2[d 17], , 12. Which of the following can be used as valid variable identifier(s) in Python?, (i) elif, (ii) BREAK, (iii) in, (iv) _Total, Ans. (ii) BREAK (iv) _Total, , 2 [compt 17], , Pr, ak, , 11. Which of the following can be used as valid variable identifier(s) in Python?, (i) total, (ii) 7Salute, (iii) Que$tion, (iv) global, Ans. (i) total, , 13. Which of the following can be used as valid variable identifier(s) in Python?, (i) 4thSum, (ii) Total, (iii) Number#, (iv) _Data, (iv) _Data, Ans. (ii) Total, , [OD 17], , 14. Which of the following is not a valid variable name in Python. Justify reason for it not being a valid name:, [comptt 2020], , (i) 5Radius, (ii) Radius_, (iii) _Radius, (iv) Radius , Ans. (i) 5Radius, , rs, , Reason: variable name in Python cannot start with a digit, , he, , 15. Which of the following are keywords in Python?, (i) break, (ii) check, (iii) range, (iii) range, Ans. (i) break, (iv) while, , (iv) while [comptt 2020], , 16. Out of the following, find those identifiers, which cannot be used for naming Variable or Functions in a Python, program:, 2 [D 16], , ot, , _Cost, Price*Qty, float, Switch, Address One,, , Br, , Delete, Number12, do, Ans. Price*Qty, float, Address One, , al, , 17. Find the correct identifiers out of the following, which can be used for naming variable, constants or functions, in a python program:, While, for, Float, new, 2ndName, A%B, Amount2, _Counter, Ans. While, Float, Amount2, _Counter, , oy, , 18. Find the correct identifiers out of the following, which can be used for naming Variable, Constants or Functions, in python program:, [OD 2015], For, while, INT, NeW, delete, 1stName, Add+Subtract, name1, Ans. For, INT, NeW, name1, , G, , 19. Out of the following, find those identifiers, which cannot be used for naming Variable, Constants or Functions in, a python program:, _Cost, Price*Qty, float, switch, Address One, Delete, Number12, do, Ans. Price*Qty, float, Address One, Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 3
Page 11 :
21. Find the invalid identifier from the following:, (i) MyName, (ii) True, (iii) 2ndName, Ans. (i) True, (ii) 2ndName, , as, ha, n, , 20. Out of the following, find those identifiers, which cannot be used for naming Variable, Constants or Functions in, a python program:, Total*Tax, double, Case, My Name, NeW, switch, Column31, _Amount, Ans. Total*Tax, My Name, 1[SP 21], , (iv) My_Name , , 22. Write the type of python keywords and user defined identifiers from the following:, (i) For, (ii) Delete, (iii) else, (iv) Value, Ans. (i) For - user defined identifier, (ii) Delete - user defined identifier, (iii) else - keyword, (iv) Value - user defined identifier, , Pr, ak, , 23. Write the type of python keywords and user defined identifiers from the following :, (i) case, (ii) _delete, (iii) while, (iv) 21stName, Ans. (i) keyword, (ii) identifier, (iii) keyword, (iv) None, 24. Write the type of python keywords and user defined identifiers from the following:, (i) in, Ans. (i) in - Keyword, (iii) and - Keyword, , (ii) While, , (iii) and, (iv) Num_2, (ii) While - User defined Identifier, (iv) Num_2 - User defined Identifier, , he, , rs, , 25. Write the type of python keywords and user defined identifiers from the following:, (i) else, (ii) Long, (iii) break, (iv) _count , Ans. (i) keyword, (ii) Identifier (iii) keyword, (iv) Identifier, 26. Identify the valid keywords in Python from the following:, (ii) False, (iii) in, (vi) method, (vii) import, (v) global (vii) import, , ot, , (i) Queue, (v) global, Ans. (ii) False (iii) in, , Br, , 27. Write the type of tokens from the following:, (i) if, (ii) roll_no, (ii) Identifier, Ans. (i) Keyword, , [2] [comptt 2020], (iv) Number, (viii) List, 1[SP 20], , , oy, , al, , (iii) Literal, Literal is a raw data given in a variable. There are various types of literals, (a) Numeric literals: Three types of numeric literals available in python: integer, float and complex, Int literals, a=123, b=839, , Float literals, x=3.14, y= 2.85, , Complex literals, z=4.13j, , (b) String literals: A string literal is a sequence of characters surrounded by quotes. We can use both single, double,, or triple quotes for a string, , G, , a= “hello”, b= ‘12345’, , (c) Boolean literals: A Boolean literal can have any of the two values: True or False, (d) Special literals: Python contains one special literal i.e. None, , 4, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 12 :
(e) Literal Collections: There are four different literal collections: List literals, Tuple literals, Dict literals, and Set, literals., (i) List literals :: [5,6,7], (ii) Tuple literals :: (1,2,3), ::, , {‘x’:1}, , (iv) Set literals, , (iv) Punctuators, Most commonly used punctuators in Python are:, ‘ “ # \ () {} [] @ , : . =, , ::, , {8,9,10}, , as, ha, n, , (iii) Dict literals, , (v) Python Operators, Python operator is a symbol that performs an operation on one or more operands. An operand is a variable or a value, on which we perform the operation. Python provides a variety of operators described as follows., •, •, , Arithmetic Operators, Membership Operators, , •, •, , Relational Operators, Identity Operators, , •, •, , Assignment Operators, Bitwise Operators, , •, , Logical Operators, , ot, , he, , rs, , Pr, ak, , (1) Arithmetic operators: Arithmetic operators are used to perform arithmetic operations between two operands. It, includes +(addition), - (subtraction), *(multiplication), /(divide), %(remainder), //(floor division), and exponent, (**)., (a) Addition(+): It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30, (b) Subtraction(-): It is used to subtract the second operand from the first operand. For example, a=30,, b=20>>> a-b=10, (c) Multiplication(*): It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a, * b = 200, (d) Division(/): It returns the quotient after dividing the first operand by the second operand. For example, if, a = 20, b = 10 => a/b = 2. If quotient is coming in float value then division results in a floating-point, value, for example, a=11,b=2 >>> a/b Output: 5.5, (e) Exponentiation(**): It returns the second operand power to first operand. a=2,b=3,a**b i.e. ab=8, (f) Floor Division(//): It returns the integer value of the quotient. It dumps the digits after the decimal. a =, 10,b = 3 => a//b = 3, (g) Modulus(%): It returns the remainder after dividing the first operand by the second operand. For example,, a = 20, b = 10 => a%b = 0, Subtraction(-), , Multiplication(*), , Division(/), , Exponentiation(**), , Floor Division(//), , Br, , Addition(+), , Modulus(%), , al, , (2) Relational Operators: Relational Operators are used to compare the value of two operands. It checks whether, an operand is greater than the other, lesser, equal, or a combination of those and returns the Boolean value i.e., True or False., , oy, , When the condition for a relative operator is fulfilled, it returns True. Otherwise, it returns False. This return, value can be used in a further statement or expression., (a) Less than(<): This operator checks if the value of first operand is less than the second operand. (i) 3<4, Output True (ii) 15<10 Output False, (b) Greater than(>): It checks if value of first operand is Greater than the second operand., , G, , >>> 3>4 Output: False, (c) Less than or equal to(<=): It checks if the value of first operand is Less than or equal to the second, operand. >>> 7<=7 Output: True, (d) Greater than or equal to(>=): It checks if the value of first operand is Greater than or equal to the second, operand. >>> 0>=0 Output: True, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 5
Page 13 :
as, ha, n, , (e) Equal to(= =): It checks if the value of first operand is Equal to the second operand. 1 is equal to the, Boolean value True, other than 1 is equal to False., (i) 5= =5 Output: True, (ii) 5= =8 Output: False, (f) Not equal to(!=): It checks if the value of two operands is not equal., (i) 5! =5 Output: False, (ii) 3!=2 Output: True, , (3) Assignment operators: The assignment operators are used to assign the value of the right expression to the left, operand. It may manipulate the value by a factor before assigning it., (a) Assign(=): It assigns the value of the right expression to the left operand., = = is used for comparing and, = is used for assigning., a=10, , print(a), , rs, , a=10, b=20, a+=b, print(a,b), output:30,20, , a=20, a+=5*2, print(a), output:30, , he, , a=10, a+=20, print(a), output :30, , Pr, ak, , output :10, (b) Add and Assign(+=): It increases the value of the left operand by the value of the right operand and assign, the modified value back to left operand., a+ = b equal to a = a+ b, , , a+=10 equal to a=a+10, , ot, , (c) Subtract and Assign(-=): It subtracts the value of the left operand by the value of the right operand and, assigns the modified value back to left operand., , a-= b equal to a = a- b, , a-=10 equal to a=a-10, a=10, b=50, a-=b, print(a,b), output:-40,50, , a=20, a-=5*2, print(a), output:10, , al, , Br, , a=20, a-=5, print(a), output :15, , G, , oy, , (d) Divide and Assign(/=): It divides the value of the left operand by the value of the right operand and assigns, the modified value back to left operand., , a/= b equal to a = a/ b, , a/=10 equal to a=a/10, , 6, , a=20, a/=5, print(a), output :4.0, , a=10, b=20, a/=b, print(a,b), output:0.5,20, , a=20, a/=5*2, print(a), output:2.0, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 14 :
(e) Multiply and Assign(*=): It multiplies the value of the left operand with the value of the right operand, and assigns the modified value back to left operand., , a*= b equal to a = a*b, , a*=10 equal to a=a*10, a=10, b=20, a*=b, print(a,b), output:200,20, , a=20, a*=5*2, print(a), output:200, , as, ha, n, , a=20, a*=5, print(a), output :100, , (f) Modulus and Assign(%=): It divides the value of the left operand by the value of the right operand and, assigns the remainder value back to left operand., , a%= b equal to a = a% b, , a%=10 equal to a=a%10, a=10, b=20, a%=b, print(a,b), output:10,20, , Pr, ak, , a=20, a%=5, print(a), output :0, , he, , a=2, a**=3, print(a), output :8, , rs, , (g) Exponent and Assign(**=): It performs exponentiation(power) the value of the left operand by the value, of the right operand and assigns the modified value back to left operand., , a**= b equal to a = a** b i.e. a=ab, , a**=10 equal to a=a**10, a=5, b=2, a**=b, print(a,b), output:25,2, , al, , Br, , ot, , (h) Floor-Divide and Assign(//=): It performs floor-division the value of the left operand by the value of the, right operand and assigns the modified value back to left operand., , a//= b equal to a = a// b, , a//=10 equal to a=a//10, a=20, a//=5, print(a), output :4, , print(10//3), output:3, , oy, , (4) Logical Operators: The logical operators are conjunctions that can be used to combine more than one condition., There are three Python logical operator – and, or, and not that come under python operators., , G, , (a) and: If all the expressions are true, then the condition will be true., a=10, b=20, a<b and b>15, output : True, , a=10, b=20, c=40, a>b and b<c and c= =40, output: False, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 7
Page 15 :
(b) or: If one of the expressions is true, then the condition will be true., a=10, b=20, c=40, a>b or b<c or c= =40, output: True, , a=10, b=20, a>b or b>20, output :False, , as, ha, n, , a=10, b=20, a<b or b>15, output : True, , (c) not: This inverts the Boolean value of an expression. It converts True to False, and False to True. If an, expression a is true then not (a) will be false and vice versa., a=10, b=20, not a>b, output : True, , not 0, Output: True, , not “xyz” = =”xyz”, output: False, , Pr, ak, , (5) Membership Python Operators : Python membership operators checks whether the value is a member of a, sequence., (a) in: It is evaluated to be true if the first operand is found in the second operand (string, list, tuple or, dictionary)., “x” in “xyz”, Output: True, , 5 in [10,20,30], Output: False, , rs, , (b) not in: It is evaluated to be true if the first operand is not found in the second operand (string, list, tuple, or dictionary)., 5 not in [10,20,30], Output: True, , he, , “x” not in “xyz”, Output: False, , ot, , (6) Python Identity Operators: Identity operators are used to verify if two variables point to the same memory, location or not. Identity operators are of two types ‘is’ and ‘is not’., (a) is: ’is’ operator returns true if both the operands point to same memory location. The variable having same, value points to same memory location; So, for them this operator returns a ‘true’., , Br, , a=10, b=10, a is b, Output :True, , a=”xyz”, b=”xyz”, a is b, output:True, , “x” is “xyz”, Output: False, , oy, , al, , (b) is not: is not operator returns true if both the operands point to different memory location. It is the opposite, of ‘is’ operator., 2 is not 2, Output :False, , “x” is not “xyz”, Output: True, , 2 is not 2.0, Output:True, , G, , (7) Bitwise Operator:, , 8, , &, Binary AND, , |, Binary OR, , ^, Binary XOR, , ~, , <<, , >>, , Binary Ones Complement, , Binary Left Shift, , Binary Right Shift, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 16 :
28. Which of the following are valid operators in Python?, (i) +=, (ii) ^, (iii) in, (vi) */, (vii) is, (viii) like, Ans. (i) +=, (ii) ^, (iii) in, (vii) is, , [comptt 19], (v) between, , (iv) &&, , [2019], , as, ha, n, , 29. Which of the following are valid operators in Python:, (i) **, (ii) */, (iii) like, (v) is, (vi) ^, (vii) between, Ans. (i) **, (v) is, (vi) ^, (viii) in, , (iv) ||, (viii) in, , , , [SP 20], , 30. Which of the following is valid arithmetic operator in Python:, (i) //, (ii) ?, (iii) <, Ans. (i) //, , (iv) and, , 31. Identify the valid arithmetic operator in Python from the following., (i) ?, (ii) <, (iii) **, (iv) and, Ans. (iii) **, , Text Type:, , string, , Numeric Types:, , int, float, complex, , Sequence Types:, , list, tuple, range, dict, , rs, , Mapping Type:, Set Types:, , set, frozenset, bool, , he, , Boolean Type:, Binary Types:, , Pr, ak, , 32. How many types of Data Type available in Python., Ans. Data Types, , [SP 21], , bytes, bytearray, memoryview, , ot, , 33. Write the names of any four data types available in Python., Integer, Boolean, Floating Point, Ans. Numbers, Strings , Tuple, List, Sets, , Complex, Mappings, , None, Dictionary, , 2[2019], Sequences, , 34. Consider the statement:, , What is the datatype of first_name ?, Is 325 the same as “325” ? Give reason., String data type, No, 325 is a Number/Integer while “325” is a String., , al, , (i), (ii), Ans. (i), (ii), , Br, , first_name = “Ayana”;, , 35. Consider the statement :, fname = “Rishabh”;, , What is the datatype of fname ?, Is 456 the same as “456” ? Give reason, String data type, No, 456 is a Number/Integer while “456” is a string., , G, , oy, , (i), (ii), Ans. (i), (ii), , 36. (i), (ii), Ans. (i), (ii), , Is 123 the same as 123.0 ? Give reason, Is “234” the same as “234.0” ? Give reason, No, 123 is an Integer. And 123.0 is a floating type., They are different strings and they are not of Number Datatype., , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 9
Page 17 :
1[2018], , 2. Operator Precedence, , as, ha, n, , 37. Write the data type of variables that should be used to store:, (i) Marks of students, (ii) Grades of students(Grade can be ‘A’ or ‘B’ or ‘C’), Ans. (i) float/int, (ii) string, , 38. What is the precedence of operators?, Ans. The precedence of an operator specifies how “tightly” it binds two expressions together. The precedence of the, operators is important to know which operator should be evaluated first. The precedence table of the operators, in python is given below:, Operator, , Description, , The exponent operator is given priority over all the others used in the expression., , ~+-, , The negation, unary plus and minus., , * / % //, , The multiplication, divide, modules, remainder, and floor division., , +-, , Binary plus and minus, , >> <<, , Left shift and right shift, , &, , Binary and., , ^|, , Binary xor and or, , <= < > >=, , Comparison operators (less than, less than or equal to, greater than, greater than, or equal to)., , <> == !=, , Equality operators., , rs, , he, , = %= /= //= -= +=, *= **=, , Assignment operators, , not or and, , Identity operators, , Membership operators, , ot, , is is not, in not in, , Pr, ak, , **, , Logical operators, , Br, , 39. Write the value that will be assigned to variable x after executing the following statement:, x = 3 + 36/12 + 2*5, , Ans. 16.0, , 40. Write the value that will be assigned to variable c after executing the following statement:, , al, , C = 25-5*4/2-10+4, , Ans. 9.0, , oy, , 41. Write the value that will be assigned to variable x after executing the following statement:, x = 20 -5 + 3 * 20/5, , Ans. 27.0, , [SP 21], , G, , 42. Evaluate the following expressions:, (a) 6 * 3 + 4**2 // 5 – 8, (b) 10 > 5 and 7 > 12 or not 18 > 3 , Ans. (a) 13, (b) False, , 10, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 18 :
3. Print function, , Pr, ak, , 43. Give the output, (i) print(20,sep=”-“,end=”$”), (ii) print(40,50,60,sep=”*“,end=”!”), (iii) print(“hello,hi,bye”,sep=”*“,end=”!”), (iv) print(“hello”,”hi”,”bye”,sep=”*”,end=”!”), (v) print(2>5,7<10,end=”@”), (vi) print(“2*3,6*5”,sep=”%”), (vii) print(2*3,6+5,sep=”+”), Ans. (i) 20$, (ii) 40*50*60!, (iii) hello,hi,bye! (iv) hello*hi*bye!, (v) False True@ , (vi) 2*3,6*5, (vii) 6+11, , as, ha, n, , The print function in Python is used to display the output of variables: string, lists, tuples, range, etc., Following is the syntax of using the print function:, print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False), Where:, • The object can be strings, lists, tuple etc., • The sep = ‘’ parameter specifies a space between multiple objects. You can use other than space by using this, parameter., • The end=’\\n\’ means in each call, the print function will end with a new line, if you want you can change that., • The file=sys.stdout specifies where the print function should send the output. is sys.stdout., • The flush keyword argument specifies whether to flush or not the output stream. The default value is false., , 4. Input() function, , he, , rs, , The input() method reads a line from input(usually user), converts into a string and returns it., The syntax of input() method is:, input([prompt]), The input() method takes a single optional argument:, prompt (Optional) - prompt is the string we wish to display on the screen. It is optional., , Practice Questions – I, , ot, , 44. What is the difference between mutable and immutable in Python?, Ans. Mutable object can be changed after it is created, and an immutable object can’t. Objects of built-in types like, (int, float, bool, string, tuple, unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable., , Br, , 45. Distinguish between ‘/’ and ‘%’ operators., Ans. ‘/’ divides first number with second number and returns the quotient., ‘%’ divides first number with second number and returns the remainder., 46. Write the output of the following Python code:, , 2 [SP 18], , G, , oy, , al, , i=5, j=7, x=0, i=i+(j-1), x=j+1, print(x,”:”,i), j=j**2, x=j+i, i=i+1, print (i,”:”,j), , Ans. 8 : 11 , , 12 : 49, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 11
Page 19 :
47. Give the output if a=10 and b=20, a=input(“enter no”), b=input(“enter 2nd no”), print(a+b), , as, ha, n, , Ans. 1020, , 48. Write a program to take two nos and swap two nos., Ans. a=int(input(“enter a”)), b=int(input(“enter b”)), a,b=b,a, print(a,b), , 49. Write a program to take two numbers and show 2nd number is power of 1st . For example if 1st number is 5, and 2nd number is 3 then result is 53 = 125, Ans. a=int(input(“enter 1st no “)), , Pr, ak, , b=int(input(“enter power”)), print(a**b), , 50. Write a program to take two nos and show the sum of these two nos., Ans. a=int(input(“enter a”)), b=int(input(“enter b”)), print(a+b), , b=float(input(“enter b”)), print(a+b), , rs, , 51. Write a program to take two float numbers and show the sum of these two., Ans. a=float(input(“enter a”)), , he, , 52. Write a program to take first name and last name from user and show full name. For example if first name is, “Aman” and last name is “Sharma” then it will display “AmanSharma”(without space)., Ans. first=input(“enter 1st name”), last=input(“enter last name”), , 53. Give the output, (i) a=20, , ot, , print(first+last), , Br, , b=30, a,b=b+20,a+30, print(a,b), , al, , Ans. 50 50, (ii) a=20, , oy, , b=30, a,c=b*10,a/10, print(a,b,c), , Ans. 300 30 2.0, (iii) a=10, , G, , b=a*20, b,c=b*10,a%10, print(a,b,c), , Ans. 10 2000 0, 12, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 20 :
Multiple Choice Questions – I, 1. Which of the following can be used as valid variable identifier(s) in Python?, (i) total, (ii) switch, (iii) Que$tion, (iv) global, (iv) float, , 3. Which of the following is invalid operator in Python?, (i) +=, (ii) ^, (iii) in, , (iv) &&, , 4. Identify invalid operator out of the following., (i) between, (ii) */, (iii) is, , (iv) //, , 5. What is the datatype of “321”?, (i) None, (ii) Integer, , (iii) String, , (iv) List, , (iii) 40!50!60,, , (iv) 40,50,60, , (iii) 21, , (iv) ”10”+”11”, , print(40,50,60,sep=”!“,end=”,”), , (i) 40,50,60!, , (ii) 40!50!60!, , 7. print(2*5,6+5,sep=”+”), output of above code is, (i) 10,11, (ii) 10+11, , 8. Write the value that will be assigned to variable x., , x = 6 + 36/6 + 2*5, , (i) 45.0, , (ii) 17.0, , Pr, ak, , 6. Output of the following code is:, , as, ha, n, , 2. Identify invalid variable name out of the following., (i) While, (ii) 123salary, (iii) Big, , (iii) 26.25, , (iv) 22.0, , (i) 10.0, , (ii) 35.0, , rs, , 9. Write the value that will be assigned to variable c., , c = 25-5*4/2-10+5, , (iii) -2.5, , (iv) -12.5, , (i) 101, , he, , 10. Write the value that will be assigned to variable a, , a=20*5+3**2%2//5, , (ii) 100, , (iii) 1.9, , (iv) None of these, , (iii) ”10+20”, , (iv) 1020, , (ii) 10,10, , (iii) 20,10, , (iv) 20,20, , (ii) 50,40, , (iii) 60,50, , (iv) 40,50, , a=”10”, c=a+b, , Br, , b=”20”, , ot, , 11. Output of the following program is, , print(c), , (i) “10”+”20”, , (ii) 30, , 12. Give the output, , al, , a,b=10,20, b,a=a,b, , print(a,b), , oy, , (i) 10,20, , 13. Give the output, , a=20, , G, , b=30, , a,b=b+10,a+30, print(a,b), , (i) 30,60, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 13
Page 21 :
a=5, b=20, a+=b, b-=a, print(a,b), , (i) 25,15, 15. Give the output, , a=16, b=3, c=a/2**b, print(c), , (i) 512.0, , as, ha, n, , 14. Give the output, , (ii) 25,5, , (iii) 25,-5, , (iv) 25,25, , (ii) 4.0, , (iii) 2.0, , (iv) 24.0, , 1. (i), 11. (iv), , 2. (ii), 12. (iii), , 3. (iv), 13. (iv), , 4. (i), 14. (iii), , 5. (iii), 15. (iii), , Pr, ak, , Answers, , 6. (iii), , 7. (ii), , 8. (iv), , 9. (i), , 10. (ii), , 5. Conditional Statement, , Conditional Statement in Python performs different computations or actions depending on whether a specific Boolean, constraint evaluates to true or false. Conditional statements are handled by IF statements in Python., , he, , if condition :, , indentedStatementBlock, , rs, , (a) IF statement: In Python if statement is a statement which is used to test specified condition. The if statement, executes only when specified condition is true., The general Python syntax for a simple if statement is, , ot, , If the condition is true, then do the indented statements. If the condition is not true, then skip the indented, statements., (b) if else statement:, The if statement accepts an expression and then executes the specified statemets If the condition is true. If the, condition is not true, then executes the specified statements indented below else., The syntax of the if...else statement is −, , Br, , if expression:, , statement(s), else:, , statement(s), , al, , (c) if-elif statement:, The elif statement allows to check multiple expressions for TRUE then execute a block of code as soon as one, of the conditions evaluates to TRUE., syntax, , G, , oy, , if expression1:, , statement(s), elif expression2:, , statement(s), elif expression3:, , statement(s), else:, , statement(s), 14, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 22 :
54. Give the output, (i) Num = 6, , as, ha, n, , Num = Num + 1, if Num > 5:, , print(Num), else:, , print(Num+5), , Ans. 7, (ii) N = 20, , N = N + 1, if N<21:, , print(N+10), else:, , print(N+15), , Pr, ak, , Ans. 36, (iii) Age,Relatxation=24,6, , ModiAge=Age-Relatxation, If ModiAge<18:, , print(“Not eligible”), else:, , print(“Eligible”), , Ans. Eligible, , rs, , 55. The following code has some error(s). Rewrite the correct code underlining all the corrections made., (i) written=int(input(“enter written marks”)), , he, , interview=input(“enter interview marks”), if (written<80 or interview <15), , print(“NotSelected”), else:, , print(“Selected”), , ot, , Ans. written=int(input(“enter written marks”)), , Br, , interview=int(input(“enter interview marks”)), if, written<80 or interview <15:, , print(“NotSelected”), else:, , print(“Selected”), , oy, , al, , (ii) marks = int(input(“enter marks”)), temperature = input(“enter temperature”), if marks < 80 and temperature >= 40, , print(“Not Good”), else, print(“OK”), Ans. marks = int(input(“enter marks”)), , G, , temperature = int(input(“enter temperature”)), if marks < 80 and temperature >= 40:, , print(“Not Good”), else:, , print(“OK”), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 15
Page 23 :
i= =j+5, if (i=j), print(“i and j are equal”), else:, print(“i and j are unequal”), , Ans., , j=5, i=j+5, if i= =j:, , print(“i and j are equal”), else:, , print(“i and j are unequal”), , 56. Write the value of p after execution of the following code:, , Pr, ak, , p=7, q=2, if p>q:, , p=p+2, p=p+1, , as, ha, n, , (iii) j=5, , Ans. 10, , , input(‘Enter a word’,W), if W = ‘Hello’, , rs, , 57. Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the, code. , [comptt 2020], , , , , Ans., , he, , , print(‘Ok’), else:, , print(‘Not Ok’), , //Error 1, //Error 2,Error 3, , ot, , W=input(‘Enter a word’), if W == ‘Hello’ :, , print(‘Ok’), , else :, , print(‘Not Ok’), , Br, , //Error 4, , oy, , al, , 58. What is the difference between the following statements (i) and (ii), (i) a = 5, (ii) if a = = 5:, x = 3, Ans. (i) variable a is being assigned the value 5, (ii) a is being checked for equality with 5, , OR, , (i) assignment operator is used, , (ii) relational operator ‘= =’ is used., , G, , 59. What is the difference between statements (i) and (ii), (i) t = 2, (ii) if, t = = 2:, , d = 3, Ans. (i) variable ‘t’ is being assigned the value 2, (ii) ‘t’ is being checked for equality with 2, 16, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 24 :
OR, (i) assignment operator is used, , , , (ii) relational operator ‘==’ is used., , 6. Loops, , as, ha, n, , Loops are used to iterate over elements of a sequence, it is often used when a piece of code which you want to repeat, “n” number of time., (a) For Loop, A for loop is used for iterating over a sequence (i.e., is either a list, a tuple or a string)., With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc., Syntax:, for var in sequence:, statements(s), , else:, , statements(s), , Pr, ak, , Here, var is the variable that takes the value of the item inside the sequence on each iteration., Else statement(s) will be executed when loop terminated normally(without break statement), , , , print(i), , , , print(i), , he, , Ans. 1, 2, 3, 4, 5, (ii) for i in 1,3,10,15:, , rs, , 60. Give the output:, (i) for i in 1,2,3,4,5:, , , , , print(i), i=i+2, , al, , Ans. 1, 3, 10, 15, , Br, , ot, , Ans. 1, 3, 10, 15, (iii) for i in 1,3,10,15:, , oy, , 61. Give the output, (i) for i in range(1,5):, , , , G, , Ans. 1, 2, 3, 4, , print(i), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 17
Page 25 :
(ii) s=0, , for i in range(1,10):, , s=s+i, print(i,s,sep=”,”), , , , print(i*i), , , , print(i*2), , , , print(i*2), , as, ha, n, , Ans. 9,45, 62. Give the output, (i) for i in range(1,5):, , Ans. 1, 4, 9, 16, (ii) for i in range(5,25,5):, , rs, , print(i), i=i+3, , he, , Ans. 10, 8, 6, 4, (iv) for i in range(1,10,2):, , Pr, ak, , Ans. 10, 20, 30, 40, (iii) for i in range(5,1,-1):, , Br, , ot, , Ans. 1, 3, 5, 7, 9, 63. What will be displayed after the execution of the following loop?, , al, , Total,End=5,15;, for Turn in range(1,End,2):, , Total+=1;, print(Total), print(Turn), , oy, , Ans. 12, 13, , 64. What will be displayed after the execution of the following loop?, , G, , sum,last=0,10, for C in range(1,last,2):, , sum=sum+1;, print(sum), print(C), , Ans. 5, 9, 18, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 26 :
65. Write the output that will be generated by the code given below:, for i in range(5,11,5):, t=i+3;, print(t), , as, ha, n, , Ans. 8, , 13, , 66. What will be the values of variables ‘P’ and ‘Q’ after the execution of the following code?, Q=0;, for P in range(1,5,1):, , , Q+=P, , , , Q=Q-1, , print(P), , Pr, ak, , print(Q), , Ans. 4, 6, , 67. What will be the values of variables ‘m’ and ‘n’ after the execution of the following code?, n=5;, for m in range(5,10,1):, n+=m, , rs, , , , n=n-1, print(n), , he, , print(m), , Ans. 35, 9, , A = 100, , , range(10, 13):, , Br, , for B in, , ot, , 68. What will be the value of A and B after execution of the following code?, , A+=B, , print(“A:”,A,”B:”,B) ;, , Ans. A: 133 B: 12, , al, , 69. What will be the value of num and num1 after execution of the following code?, num1=10, , oy, , for num in range(100,102):, , , num1=num+2, , , , num1=num1-1, , G, , print(num), print(num1), , Ans. 101, 102, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 19
Page 27 :
70. What will be the values of x and y after execution of the following code?, y=0;, , for x in range(1,6):, , , y=x+1, , y=y-1, , as, ha, n, , , , print(x), print(y), , Ans. 5, 5, , 71. Write the value that will be stored in variable sum after execution of following code?, sum=0, , , if(i%3==0):, , , , else:, , , , sum = sum + i, , , , sum = sum - i, , print(i,sum), , Pr, ak, , for i in range(9,5,-1):, , Ans. 6 0, , 72. What will be displayed after the following code is executed?, n=3;, , rs, , p=1;, , if n < 0:, else:, , , , he, , print(“Not Valid”), for i in range(1,n+1):, p = p* i;, , ot, , print(n+p), , Ans. 9, , R= 8;, , Br, , 73. Write the value of C after executing the following code, C = 0;, , for P in range(1,R,3):, , , if oddNum == 1:, , al, , , , oddNum = P %2;, , , , oy, , print(C), , C= C+1, , Ans. 2, , (b) While loop, , G, , While loop repeats the sequence of actions many times until some condition evaluates to False, while condition:, , , block of statement(s), , The else part is executed if the condition in the while loop evaluates to False., 20, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 28 :
74. How many times will the following loop execute and give the output, z=7, , sum=0;, , , , sum=sum+z, z=z+2, , print(z), , Ans. 3 times, 11, , 75. How many times does the following while loop get executed?, K=5, , L=36, , while K<=L:, , Ans. 6, , K+=6, , Pr, ak, , , , 76. How many times will the loop execute?, value1,value2=7,19;, , while value1<=value2:, , , Ans. 4, , value1=value1+2, value2=value2-2, , rs, , , , as, ha, n, , while z<=12:, , y,sum=7,0, , while y<=15:, , , sum = sum + y, y = y+2, , print(sum), , ot, , , , he, , 77. How many times will the following WHILE loop execute and what will be the value of sum after execution of, the following loop?, , Ans. loop will be executed 5 times and value of sum is 55, a=9, , agg=9, , Br, , 78. What will be the values of variables agg after execution of the following loops?, , while(a>10):, agg+=a, , al, , , , , a-=2, , oy, , Ans. agg=9,, , 79. What will be the values of variables sum after execution of the following loop?, , v=6, , sum=0, , G, , while v>3:, , , , Ans. 10, , sum+=v;, v-=2, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 21
Page 29 :
80. What will be displayed after the execution of the following code?, G=1, , while G<=5:, , print(G+2), , , , Ans. 3, , G=G+1, , 4, 5, 6, 7, 81. What will be displayed after the execution of the following code?, z=4, , , , Ans., , Pr, ak, , while z<=8:, , print(z+3), , 7, , as, ha, n, , , , z=z+2, , 9, 11, , 82. Write the output that will be generated by the code given below:, , rs, , i=7, r=8, , , , Ans. 56, , print(r*i), i=i+2, , 72, , ot, , , , he, , while i<=10:, , 83. Observe the following code carefully and find which statement will never get executed in the code:, #statement1, , Br, , counter=1, , while counter<=15:, , , if counter<15:, , #statement3, , print(“Jump”), , #statement4, , else:, , #statement5, , al, , , , #statement2, , print(“Stop”), , #statement6, , counter+=4, , #statement7, , oy, , Ans. statement 6, , 84. Find and write the output of the following python code:, , 1[SP 2019-20], , x = “abcdef”, , G, , i = “a”, , while i in x:, , , print(i, end = “ “), , , , Ans. aaaaaa----- OR infinite loop, , 22, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 30 :
85. Write the value that will be stored in variable p after execution of following code. How many times will the, loop execute?, y,x,p = 3,5,0, while y > 0:, , , Ans. p=15, , p = p + x, , as, ha, n, , , , y = y-1, , 3 times, , 86. What will be displayed after the following code is executed? Also write how many times will the loop execute., a = 5;, b = 2;, , while (b != 0):, , , r = a%b, , , , b = r, , a = b, , Pr, ak, , , , print(a), , Ans. 1, , 2 times, , 87. Write the value that will be stored in variable num and sum after execution of following code:, num = -2, , while num < 1 :, , , sum = sum + num, num=num+1, , Ans. num = 1 sum = -3, , he, , , , rs, , sum=0, , ndigits = 0, N = 35, , ot, , 88. What will be displayed after the following code is executed?, , , , , Br, , while (N > 12):, , ndigits = ndigits + 1, N = N-10;, , print(ndigits), , al, , print(N), , Ans. 3, , oy, , 5, , 89. What will be the final value of variable x after the following code is executed?, , [SP 18], , x=10, , while x>1:, , G, , , , , x=x//3, x=x+1, , print(x), , Ans. 1, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 23
Page 31 :
90. What will be the output displayed, when the following code is executed?, , [2018], , a=5, , b = 2, , , a = a + b, , , , b = a - b, , print(a,end=” “), , Ans. 7 12 19 31, , 91. What will be the values of i and z after the following code is executed?, i = 0, , z = 10, , while i<10:, , , i=i+2, z=z-1, , Pr, ak, , , , as, ha, n, , while a < 20:, , print(i,z), , Ans. 10, 5, , Theory, , 92. What do you understand by the term Iteration?, Ans. Repeatation of statement/s finite number of times is known as Iteration., , if i = = 3:, , , , print i, , , , break, , ot, , The output of the above code will be:, 0, 1, 2, The loop terminates when i becomes 3 due to break statement whereas, continue statement is used to force the, next iteration while skipping the statements in the present iteration., , Br, , , , , , , , 2 [SP 18], , he, , for i in range(6):, , , [SP 2019-20], , rs, , 93. Differentiate between break and continue statement with the help of an example., Ans. Break statement is used to terminate the execution of the loop, for example:, , [2018], , for i in range(6):, if i ==3:, , al, , continue, print i, , The output of the above code will be, 0, 1, 2, 4, 5, continue statement forces next iteration when i becomes 3 , bypassing the print statement .Thus ,in the output 3, is missing., , G, , oy, , , , , , , , , 24, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 32 :
7. LIST, , The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items), between square brackets. Important thing about a list is that items in a list need not be of the same type., , as, ha, n, , Creating a list, In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ], separated by, commas. It can have any number of items and they may be of different types (integer, float, string etc.)., Empty List, lt=[], print (lt), , output, [], , Pr, ak, , Creating list with same type, lt=[2,4,5], lt1=[‘hello’,’hi’,’bye’], lt2=[25.7,35.8,93.2], print (lt), print (lt1), print (lt2), , rs, , output:, [2, 4, 5], [‘hello’, ‘hi’, ‘bye’], [25.7, 35.8, 93.2], , he, , List within list, , lt=[[2,4,5],[‘hello’,’hi’,’bye’],25.7,35.8,93.2], print (lt), , ot, , [[2, 4, 5], [‘hello’, ‘hi’, ‘bye’], 25.7, 35.8, 93.2], List with different data types, , Br, , lt=[1,’rahul’,18,87.5], print (lt), , , [1, ‘rahul’, 18, 87.5], , oy, , al, , Access Elements, To retrieve an element of the list, we use the index operator ([]). Index starts from 0. Trying to access an element other, that this will raise an IndexError. The index must be an integer. We can’t use float or other types, this will result into, TypeError, Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item, and so on., , G, , 94. A List L contain the following values, L=[10,20,30,40,50,60,70,80], show the output of following print statements, (i) print(L[1]), , (ii) print(L[3]), , (iii) print(L[-2]), , (iv) print(L[-6]), , (v) print(L[4],L[-3]), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 25
Page 33 :
Ans. The index values of List are:, 1, , 2, , 3, , 4, , 5, , 6, , 7, , 10, , 20, , 30, , 40, , 50, , 60, , 70, , 80, , -8, , -7, , -6, , -5, , -4, , -3, , -2, , -1, , (ii) 40, , (iii) 70, , (iv) 30, , Using for loop, 95. A list lt is given below, show all contents of list using for loop, lt=[2,4,5], Ans. for i in lt:, 2, 4, 5, , print(i), , Pr, ak, , , , (v) 50 60, , as, ha, n, , (i) 20, , 0, , Using slicing, A slice is a subset of list elements., my_list[start:stop,step], where start is the index of the first element to include, stop is the index of the item to stop at without including it in, the slice and step sets the interval, 96. Give the output, , he, , ot, , [4], [2, 4, 5], [5, 8, 10, 15], [2, 4, 5, 8, 10, 15], [5, 8], [10, 8, 5], , Br, , Ans., , , , , , , rs, , lt=[2,4,5,8,10,15], print(lt[1:2]), print(lt[:3]), print(lt[2:]), print(lt[:]), print(lt[2:-2]), print(lt[-2:-5:-1]), , al, , Changed Item Value, We can use assignment operator (=) to change an item or a range of items., 97. Give the output of the following program, , G, , oy, , lt=[2,4,5,8,10,15], lt2=[[‘one’,’two’,’three’],[4,5,6]], lt[1]=9, lt2[0][2]=2, lt2[-1][0]=5, print(lt), print(lt2), , Ans. [2, 9, 5, 8, 10, 15], , [[‘one’, ‘two’, 2], [5, 5, 6]], 26, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 34 :
Adding new Element(s), By append method : Add an element to the end of the list, 98. Give the output, lt=[1,0,5,8,10,15], , as, ha, n, , lt2=[[‘one’,’two’,’three’],[4,5,6]], lt.append(25), lt2.append(7), for i in range (1,4):, , , lt.append(i*2), , print(lt), print(lt2), , [[‘one’, ‘two’, ‘three’], [4, 5, 6], 7], Adding tuple and list, 99. Give the output, tup1=(7,8,9), lt=[1,0,5,8,10,15], lt2=[[‘one’,’two’,’three’],[4,5,6]], , rs, , lt.append(tup1), lt2.append(lt), , he, , print(lt), print(lt2), , Pr, ak, , Ans. [1, 0, 5, 8, 10, 15, 25, 2, 4, 6], , Ans. [1, 0, 5, 8, 10, 15, (7, 8, 9)], , [[‘one’, ‘two’, ‘three’], [4, 5, 6], [1, 0, 5, 8, 10, 15, (7, 8, 9)]], , ot, , Using insert() method, , Addition of Element at specific Position, , Br, , insert(position,no), , 100. List lt and lt2 are given to you, write command to add 15 on position 1 in lt and add 8 on position 1 in lt2, lt=[1,0,5,8,10,15], , lt2=[[‘one’,’two’,’three’],[4,5,6]], , al, , Ans. lt.insert(1,15) # 1 is position, 15 is no to add, lt2.insert(1,8), , oy, , print(lt), , print(lt2), output, , G, , [1, 15, 0, 5, 8, 10, 15], [[‘one’, ‘two’, ‘three’], 8, [4, 5, 6]], Using extend method, Addition of multiple elements to the List at the end, Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 27
Page 35 :
101. Give the output, lt=[1,0,5,8,10,15], , lt2=[[‘one’,’two’,’three’],[4,5,6]], lt.extend([20,34,66]), , as, ha, n, , lt2.extend([4,8,6]), , lt.extend(range(15,20)), print(lt), , print(lt2), , Ans. [1, 0, 5, 8, 10, 15, 20, 34, 66, 15, 16, 17, 18, 19], [[‘one’, ‘two’, ‘three’], [4, 5, 6], 4, 8, 6], , 102. Give the output, L=[10,20,30,40,50], L[len(L):]=45,67, print(L), , Ans. [10, 20, 30, 40, 50, 45, 67], , Pr, ak, , Using slicing, You can add elements in list by using slicing, , Remove Item(s) from List, , rs, , Using remove() method : Removes an item from the list, , 103. Write a command to delete 1st occurance of 5 from list lt, lt=[1,0,5,8,10,5], , he, , Ans. lt.remove(5), print(lt), , [1, 0, 8, 10, 5], , Br, , 104. Give the output, , ot, , Using pop() method, The pop() method removes the specified index, (or the last item if index is not specified):, lt=[1,0,4,5,8,2,3,10,5], lt.pop(), , lt.pop(2), , #remove no of index no 2, , al, , lt.pop(4), , #remove last no, , print(lt), , oy, , Ans. [1, 0, 5, 8, 3, 10], clear(): is used to clear all items from list, 105. Removes all items from the list lt, , lt=[1,0,4,5,8,2,3,10,5], , G, , Ans. lt.clear(), print(lt), output, [], 28, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 36 :
Using del, The del keyword removes the specified index, 106. Give the output, lt=[1,0,4,5,8,2,3,10,5], , as, ha, n, , del lt[1], print(lt), , Ans. [1, 4, 5, 8, 2, 3, 10, 5], The del keyword can also delete the list completely:, 107. Give the output, lt=[1,0,4,5,8,2,3,10,5], del(lt), , print(lt), , Pr, ak, , Ans. NameError: name ‘lt’ is not defined, Sorting, , 108. (i) Write program in python to sort items in a list lt in ascending order, lt=[1,0,4,5,8,2,3,10,5], , lt.sort(), print(lt), Output;, [0, 1, 2, 3, 4, 5, 5, 8, 10], , (ii), , Write program in python to sort items in a list lt in descending order, , ot, , , Ans. lt.sort(reverse=True), print(lt), Output:, [10,8,5,5,4,3,2,1,0], , he, , lt=[1,0,4,5,8,2,3,10,5], , rs, , Ans., , , , , Br, , Index(), Returns the index of the first matched item, 109. Give the output, , lt=[1,0,4,5,8,2,3,10,5], print(lt.index(5)), , al, , Ans. 3, , oy, , Reverse():, Reverse the order of items in the list, 110. Write a command to show the contents of list lt in reverse order, , lt=[1,0,4,5,8,2,3,10,5], , G, , Ans. lt.reverse(), print(lt), output:, , [5, 10, 3, 2, 8, 5, 4, 0, 1], Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 29
Page 37 :
sum(),min(),max(),count(), 111. Write a program in pyhon to display the sum, maximum value, maximum value and no of items in list lt, lt=[1,0,4,5,8,2,3,10,5], Ans. a=sum(lt), , as, ha, n, , b=max(lt), c=min(lt), d=lt.count(5), print (a), print (b), print (c), print (d), , Pr, ak, , , 38, 10, 0, 2, , Output :List, , 112. Find and write the output of the following python code :, , he, , Br, , Ans. Jayes, Finished, Ramya, Finished, Taruna, Got it!, , ot, , print (“Got it!”), , 2 [D 15], , rs, , for Name in [“Jayes”, “Ramya”, “Taruna”, “Suraj”]:, print (Name), if Name[0]== “T”:, , break, else:, , print (“Finished”), , 113. Give the output, , 2 [OD 15], , oy, , al, , for Name in [‘John’, ‘Garima’,’Seema’,’Karan’]:, print (Name), if Name[0]==’S’:, , break, else:, , print (‘Completed!’), print(‘Weldone!’), , G, , Ans. John, Completed!, Garima, Completed!, Seema, Weldone!, 30, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 38 :
STR = [“90”,”10”,”30”,”40”], COUNT = 3, SUM = 0, for I in [1,2,5,4]:, S = STR[COUNT], SUM = float (S)+I, print (SUM), , , Ans., , , , , COUNT-=1, , 41.0, 32.0, 15.0, 94.0, , rs, , Ans. 3 : 1600, 2600, , 2[comptt 17], , Pr, ak, , 115. Find and write the output of the following Python code :, , L1 = [100,900,300,400,500], START = 1, SUM = 0, for C in range (START,4):, SUM = SUM + L1[C], print (C,”:”,SUM), SUM = SUM + L1[0]*10, print (SUM), , [D 17], , as, ha, n, , 114. Find and write the output of the following Python code:, , he, , 116. Find and write the output of the following python code:, , 2 [OD 17], , , , 47.0, 35.0, 54.0, 26.0, , CNT-=1, , al, , Ans., , , , , Br, , ot, , TXT=[“20”,”50”,”30”,”40”], CNT = 3, TOTAL = 0, for C in [7,5,4,6]:, , T = TXT[CNT], , TOTAL = float (T) + C, , print (TOTAL), , oy, , 117. What output will be generated when the following Python code is executed?, , [SP 17], , G, , def ChangeList():, , L=[ ], , L1=[ ], , L2=[ ], , for i in range(1,10):, , L.append(i), , for i in range(10,1,-2):, Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 31
Page 39 :
Ans. [11, 10, 9, 8, 7, 4], , 118. Write the output of the following Python program code:, , as, ha, n, , , L1.append(i), , for i in range(len(L1)):, , L2.append(L1[i]+L[i]), , L2.append(len(L)-len(L1)), , print (L2), ChangeList(), , Pr, ak, , Data=[“D”,”o”,” “,”I”,”t”,” “,”@”,” “, “1”,”2”,”3”,” “,”!”], for i in range(len(Data)-1):, , if(Data[i].isupper()):, , Data[i]=Data[i].lower(), , elif (Data[i].isspace()):, , Data[i]=Data[i+1], print(Data), , [SP 18], , Ans. [‘d’, ‘o’, ‘I’, ‘i’, ‘t’, ‘@’, ‘@’, ‘1’, ‘1’, ‘2’, ‘3’, ‘!’, ‘!’], , 119. Find and write the output of the following python code:, , Numbers=[9,18,27,36], for Num in Numbers:, , for N in range(1, Num%8):, , print(N,”#”,end=”” ), , print(), , rs, , Ans. 1 #, 1 #2 #, 1 #2 #3 #, , he, , 120. Find and write the output of the following python code:, , Br, , Ans. 1 *, 1 *2 *, 1 *2 *3 *, , 121. Find and write the output of the following python code:, = [“P”,20,”R”,10,”S”,30], = 0, = “”, = 0, in range(1,6,2):, Times= Times + C, Alpha= Alpha + Data[C-1]+”$”, Add, = Add + Data[C], print (Times,Add,Alpha), , 2 [D 18], , G, , oy, , al, , Data, Times, Alpha, Add, for C, , , , , , 2 [OD 16], , ot, , Values=[10,20,30,40], for Val in Values:, , for I in range(1, Val%9):, print(I,”*”,end= “” ), , print(), , 2 [D 16], , Ans. 1 20 P$, 4 30 P$R$, 9 60 P$R$S$, 32, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 40 :
122. Give the output, , [2][comptt 2020], , :, 5, :, 3, , as, ha, n, , def ChangeVal(M,N):, , for i in range(N):, , if M[i]%5 == 0, , M[i] //=, , if M[i]%3 == 0, , M[i] //=, L=[ 25,8,75,12], ChangeVal(L,4), for i in L :, , print(i, end=’#’), , 123. Give the output, (i) lt=[2,4,5], , lt1=[‘sun’,’mon’,’tue’], lt2=[[‘one’,’two’,’three’],[4,5,6]], print(lt[0]), print(lt1[-2]), print(lt2[0][1]), print(lt2[-1][-1]), print(lt2[0][1]), , he, , rs, , Ans. 2, mon, two, 6, , Pr, ak, , Ans. 5#8#5#4#, , two, (ii) lt2=[[‘one’,’two’,’three’],[4,5,6]], , , , ot, , for i in lt2:, , for j in i:, , print(j,end=””), print(), , Br, , Ans. onetwothree, , 456, (iii) lt=[1,0,5,8,10,15], , oy, , al, , lt2=[[‘one’,’two’,’three’],[4,5,6]], lt[1]=lt[0], lt[0]=lt[1], lt2[-1][0]=lt[2]+3, print(lt), print(lt2), , G, , Ans. [1, 1, 5, 8, 10, 15], [[‘one’, ‘two’, ‘three’], [8, 5, 6]], (iv) L=[10,20,30,40,50], L[1:3]=45,67, print(L), , Ans. [10, 45, 67, 40, 50], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 33
Page 41 :
(v) lt=[1,0,4,5,8,2,3,10,5], , Ans. [0, 5, 8, 10, 5], (vi) lt=[1,0,4,5,8,2,3,10,5], , lt2=[[‘one’,’two’,’three’],[5,4,6]], lt2[0].sort(), #descending, lt.sort(reverse=True), print(lt), print(lt2), , order, , Ans. [10, 8, 5, 5, 4, 3, 2, 1, 0], [[‘one’, ‘three’, ‘two’], [4, 5, 6]], (vii) lt2=[[‘one’,’two’,’three’],[5,4,6]], , Pr, ak, , lt2.reverse(), print(lt2), , as, ha, n, , for i in range(1,5):, , lt.remove(i), print(lt), , [[5, 4, 6], [‘one’, ‘two’, ‘three’]], , 8. TUPLE, , rs, , A Tuple is a collection of Python objects separated by commas., • Tuples are written with round brackets(parentheses are optional), whereas lists use square brackets., • Tuple is immutable unlike lists which are mutable. we cannot change the elements of a tuple once it is assigned, whereas, in a list, elements can be changed., • Tuple indices start at 0., • A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.)., [SP 21], , ot, , he, , 124. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect?, (a) print(T[1]), (b) T[2] = -29, (c) print(max(T)), (d) print(len(T), Ans. (b) T[2]= -29 (as tuple is immutable), 125. A tuple is declared as, , Br, , T = (2,5,6,9,8), , What will be the value of sum(T)?, Ans. 30, , , , [SP 21], , 9. STRING, , al, , Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters., However, Python does not have a character data type, a single character is simply a string with a length of 1. Strings, in Python can be created using single quotes or double quotes or even triple quotes., , oy, , 126. The following code has error(s), rewrite the correct code underlining all the correction made:, , str1=Seema, for b range (0;3,1):, , print(str1+b,last=”*”), , G, , Ans., , str1=”Seema”, for b in range (0,3,1):, , print(str1+str(b),end=”*”), 34, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 42 :
127. Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the, code, [D 17], TEXT=””GREAT, DAY””, , , as, ha, n, , for T in range[0,7]:, , printTEXT(T), , print T+TEXT, , Ans., , TEXT=”GREAT”, DAY=””, , for T in range(0,7):, , , print (TEXT[T]), , print (T,TEXT), , Pr, ak, , 128. Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the, code., , print (S,STRING), , he, , print S+STRING, Ans. STRING=”WELCOME”, NOTE=” “, for S in range(0,5):, , print (STRING[S]), , rs, , STRING=””WELCOME, NOTE””, for S in range[0,8]:, , print STRING(S), , 129. Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the, code., [OD 17], , Br, , ot, , STRING=””WELCOME, NOTE””, for S in range[0,8]:, , print STRING(S), print S+STRING, , Ans. STRING=”WELCOME”, , oy, , al, , NOTE=” “, for S in range(0,8):, , print (STRING[S]), print (S,STRING), , 10. Dictionary, , A dictionary in Python is just like a dictionary in the real world. Python Dictionary are defined into two elements Keys, and Values., , G, , Features of Dictionary:, Keys are unique within a dictionary while values may not be., • The values of a dictionary can be of any type., • The keys must be of an immutable data type such as strings, numbers, or tuples., , •, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 35
Page 43 :
Keys will be a single element, , •, , Each key-value pair maps the key to its associated value., , •, , Dictionary can be defined by enclosing a comma-separated list of key-value pairs in curly braces ({})., , •, , A colon (:) separates each key from its associated value:, , •, , Dictionary is mutable means additon and modification can be done., , 130. Give the output, dic1={1:”aman”,3:”abha”,2:”shanker”}, dic2={‘name’:”aman”,’rollno’:[1,2,3,4]}, dic3={‘name’:(“raj”,”aman”,”pahul”),’rollno’:[1,2,3,4]}, print(dic1.items()), print(dic2.items()), print(dic3.items()), , Pr, ak, , Ans. dict_items([(1, ‘aman’), (3, ‘abha’), (2, ‘shanker’)]), , as, ha, n, , •, , dict_items([(‘name’, ‘aman’), (‘rollno’, [1, 2, 3, 4])]), , dict_items([(‘name’, (‘raj’, ‘aman’, ‘pahul’)), (‘rollno’, [1, 2, 3, 4])]), , 131. Create dictionary dic1 with rollno (1,5,7) as keys and names(“aman”,”abha”,”shanker”) as respective values., Ans. dic1={1:’aman’,5:’abha’,7:’shanker’}, 132. Give the output:, for i in dic1:, , Ans. output:, , print (i,end=’’), , rgb, , he, , , , rs, , dic1={‘r’:’red’,’g’:’green’,’b’:’blue’}, , 133. Write the names of the immutable data objects from the following:, (ii) Tuple, , ot, , (i) List, Ans. (ii) Tuple (iii) String, , (iii) String, , [1][comptt 2020], (iv) Dictionary , , Br, , 134. Write a Python statement to declare a Dictionary named ClassRoll with Keys as 1,2,3 and corresponding values, as ‘Reena’, ‘Rakesh’, ‘Zareen’ respectively., [1][comptt 2020], Ans. ClassRoll = {1:”Reena”, 2:”Rakesh”, 3: ”Zareen”}, , al, , 135. Write a statement in Python to declare a dictionary whose keys are 1, 2, 3 and values are Monday, Tuesday and, Wednesday respectively., [SP 21], Ans. Day={1:’monday’,2:’tuesday’,3:’wednesday’}, , oy, , Theory, , 136. What is a NameError in Python?, [1][comptt 2020], Ans. NameError is a syntax error raised when a local or global name used in a Python code is not found., , G, , 137. What is a TypeError in Python?, [1][comptt 2020], Ans. TypeError is a syntax error raised, when an operation or function is applied to an object of inappropriate type in, a Python code., , 36, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 44 :
Multiple Choice Questions – II, 1. Which of the option out of (i) to (iv) is the correct data type for the variable Vowels as defined in the following, Python statement:, (i) List, , (ii) Dictionary, , (iii) Tuple, , (iv) Array [1] [comptt 2020], , 2. Which is the correct form of declaration of dictionary?, (i) Day={1:’monday’,2:’tuesday’,3:’wednesday’}, (ii) Day=(1;’monday’,2;’tuesday’,3;’wednesday’), (iii) Day=[1:’monday’,2:’tuesday’,3:’wednesday’], (iv) Day={1’monday’,2’tuesday’,3’wednesday’] 1, 3. Identify the valid datatype of L:, L = [1, 23, ‘hi’, 6], (i) list, (ii) dictionary, , as, ha, n, , Vowels = (‘A’, ‘E’, ‘I’, ‘O’, ‘U’), , [SP 2019-20], , [SP 2019-20], , (iii) array, , (iv) tuple, , , , Pr, ak, , 4. Krrishnav is looking for his dream job but has some restrictions. He loves Delhi and would take a job there if, he is paid over `40,000 a month. He hates Chennai and demands at least `1,00,000 to work there. In any another, location he is willing to work for `60,000 a month. The following code shows his basic strategy for evaluating, a job offer., Code:, [CBSE QB], , #Statement 1, , rs, , pay= _________, location= _________, if location == “Mumbai”:, print (“I’ll take it!”), elif location == “Chennai”:, if pay < 100000:, print (“No way”), else:, print(“I am willing!”), elif location == “Delhi” and pay > 40000:, , print(“I am happy to join”), elif pay > 60000:, , print(“I accept the offer”), else:, , print(“No thanks, I can find something better”), , he, , #Statement 2, #Statement 3, , Br, , ot, , #Statement 4, , G, , oy, , al, , On the basis of the above code, choose the right statement which will be executed, and location are given., (i) Input: location = “Chennai”, pay = 50000, (a) Statement 1, (b) Statement 2, (c) Statement 3, (ii) Input: location = “Surat” ,pay = 50000, (a) Statement 2, (b) Statement 4, (c) Statement 5, (iii) Input: location = “Any Other City”, pay = 1, (a) Statement 1, (b) Statement 2, (c) Statement 4, (iv) Input: location = “Delhi”, pay = 500000, (a) Statement 6, (b) Statement 5, (c) Statement 4, (v) Input: location = “Lucknow”, pay = 65000, (a) Statement 2., (b) Statement 3, (c) Statement 4, , #Statement 5, #Statement 6, , when different inputs for pay, , (d) Statement 4, (d) Statement 6, (d) Statement 6, (d) Statement 3, (d) Statement 5, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 37
Page 45 :
5. Consider the following code and answer the questions that follow:, , [CBSE QB], , Book={1:’Thriller’, 2:’Mystery’, 3:’Crime’, 4:’Children Stories’}, Library ={‘5’:’Madras Diaries’,’6’:’Malgudi Days’}, , as, ha, n, , (i) Ramesh needs to change the title in the dictionary book from ‘Crime’ to ‘Crime Thriller’. He has written, the following command:, , Book[‘Crime’]=’Crime Thriller’, , But he is not getting the answer. Help him choose the correct command:, , (b) Book[3]=’Crime Thriller’, , (a) Book[2]=’Crime Thriller’, , (c) Book[2]=(’Crime Thriller’), , (d) Book[3] =(‘Crime Thriller’), , (ii) The command to merge the dictionary Book with Library the command would be:, (a) d=Book+Library , , (b) print(Book+Library), , (c) Book.update(Library) , , (d) Library.update(Book), , print(list(Library)), , (a) [‘5’,’Madras Diaries’,’6’,’Malgudi Days’], , (c) [’Madras Diaries’,’Malgudi Days’], , Pr, ak, , (iii) What will be the output of the following line of code:, , (b) (‘5’,’Madras Diaries’,’6’,’Malgudi Days’), , (d) [‘5’,’6’], , (iv) In order to check whether the key 2 is present in the dictionary Book, Ramesh uses the following command:2, in Book He gets the answer ‘True’., Now to check whether the name ‘Madras Diaries’, ‘Madras Diaries’ in Library, , rs, , exists in the dictionary Library, he uses the following command:, , But he gets the answer as ‘False’. Select the correct reason for this:, , he, , (a) We cannot use the in function with values. It can be used with keys only., (b) We must use the function Library.values() along with the in operator, (c) We can use the Library.items() function instead of the in operator, (d) Both (b) and (c) are correct., , ot, , (v) With reference to the above declared dictionaries, predict the output of the following code fragments, Code 1, , Code 2, Library=Book.copy(), , print(Library), , print(Library), , Br, , Library=Book, , Library.pop(2), , al, , print(Book), , Library.pop(2), print(Book), , G, , oy, , (a), , 38, , Code 1, , Code 2, , {1: ‘Thriller’, 2:, ‘Mystery’, 3: ‘Crime’,, 4: ‘Children Stories’}, , {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , 1: ‘Thriller’, 2:, ‘Mystery’, 3: ‘Crime’,, 4: ‘Children Stories’}, , {{1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 46 :
(b), Code 1, , Code 2, {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , {1: ‘Thriller’, 2:, ‘Mystery’, 3: ‘Crime’,, 4: ‘Children Stories’}, , {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , as, ha, n, , {2:’Mystery’}, , (c), Code 1, , Code 2, {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , Pr, ak, , {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , {1: ‘Thriller’, 2:, ‘Mystery’, 3: ‘Crime’, 4:, ‘Children Stories’}, , (d), Code 1, , he, , {1: ‘Thriller’, 2:, ‘Mystery’, 3: ‘Crime’,, 4: ‘Children Stories’}, , {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , rs, , {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , Code 2, , {1: ‘Thriller’, 3:, ‘Crime’, 4: ‘Children, Stories’}, , ot, , 6. Priyank is a software developer with a reputed firm. He has been given the task to computerise the operations, for which he is developing a form which will accept customer data as follows:, [CBSE QB], , Br, , The DATA TO BE ENTERED IS :, (A) Name , (B) Age, , (C) Items bought( all the items that the custom bought), , al, , (D) Bill amount, , (i) Choose the most appropriate data type to store the above information in the given sequence., (b) string, integer, dictionary, float, , (c) string, integer, integer, float, , (d) string, integer, list, float, , G, , oy, , (a) string, tuple, float, integer , , (ii) Now the data of each customer needs to be organised such that the customer can be identified by name, followed by the age, item list and bill amount. Choose the appropriate data type that will help Priyank, accomplish this task., (a) List , , (b) Dictionary, , (c) Nested Dictionary, , (d) Tuple, , , , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 39
Page 47 :
(iii) Which of the following is the correct way of storing information of customers named ‘Paritosh’ and, ‘Bhavesh’ with respect to the option chosen above?, (a) a.customers= {‘Paritosh’:24,[‘Printed Paper’, ‘ Penstand’], 3409, ‘Bhavesh’:, 45,[‘A4 Rim’,’Printer Cartridge’, ‘Pen Carton’, ‘Gift Wrap’], 8099.99 }, , as, ha, n, , (b) customers={‘Paritosh’:[24,[‘Printed Paper’, ‘ Penstand’], 3409], ‘Bhavesh’:, [45,[‘A4 Rim’,’Printer Cartridge’, ‘Pen Carton’, ‘Gift Wrap’],, , 8099.99] }, , (c) customers= [‘Paritosh’:24,‘Printed Paper’, ‘ Penstand’, 3409, ‘Bhavesh’:, 45,‘A4 Rim’,’Printer Cartridge’, ‘Pen Carton’, ‘Gift Wrap’, 8099.99 ], , (d) customers=(‘Paritosh’:24,[‘Printed Paper’, ‘ Penstand’], 3409, ‘Bhavesh’:, , 45,[‘A4 Rim’,’Printer Cartridge’, ‘Pen Carton’, ‘Gift Wrap’], 8099.99 ), , (iv) In order to calculate the total bill amount for 15 customers, Priyank, , , Statement 1. must use a variable of the type float to store the sum., , Pr, ak, , , Statement 2. may use a loop to iterate over the values, (a) Both statements are correct., , (b) Statement 1 is correct, but statemnt 2 is not., (c) Both statements are incorrect., , (d) Statement 1 is incorrect but statement 2 is correct., , rs, , 7. Write the value that will be stored in variable t after the execution of the following code. How many times will, the loop execute?, sum = score = 0, while score <=3:, score = score +1, , , , sum = sum + score, , t = sum // 3, , ot, , print(t), , he, , , , Loop executes 3 times, , (ii) Value of t will be 3, , Loop executes 4 times, , (iii) Value of t will be 3, , Loop executes 3 times, , (iv) Value of t will be 4, , Loop executes 4 times, , Br, , (i) Value of t will be 4, , 8. Observe the following code carefully and find which statement will never get executed in the code?, #statement1, , while(t<=15):, , #statement2, , , , #statement3, , al, , t=1, , oy, , if t>13:, , , , , else:, , , , G, , , , 40, , print(“Something”), , #statement4, #statement5, , print(“Pass”), , t+=3, , #statement6, #statement7, , (i) statement 1 , , (ii) statement 2, , (iii) statement 3 , , (iv) statement 4, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 48 :
9. Write the value of sum1 after execution of the following WHILE loop :, i = 1, , sum1 = 0, , , , (i) 24, , sum1 =sum1+ i, i =i+2, , (ii) 25, , (iii) 26, , (iv) 27, , (iii) 1*4*7*, , (iv) 1*4*7*10, , 10. Give the output, for i in range(1,10,3):, , , print(i,sep=”-”,end=”*”), , (i) 1-4-7*, , (ii) 1-4-7-10*, , as, ha, n, , while i<10:, , 11. If the following code is executed, what will be the output of the following code?, print(name[3:10]), , (i) mputerS , , (ii) puterSc , , Pr, ak, , name=”ComputerSciencewithPython”, , (iii) mputerScie (iv) puterScien, , (i) 32 , , (ii) 16 , , (iii) 17 , , (iv) 31, , he, , print(m+15), , rs, , 12. m = 16, m = m+1, if m<15:, , print(m), else:, , , [SP 21], , Answers, , 3., (ii), (ii), (ii), 9., , (i), (d), (d), (b), (ii), , (iii), (iii), (iii), 10., , (d) (iv) (c), (d) (iv) (b), (b) (iv) (a), (iii) 11. (i), , ot, , (i), (b), (b), (d), (iv), , Br, , 2., (i), (i), (i), 8., , (v) (d), (v) (c), , 12. (i), , G, , oy, , al, , 1. (iii), , 4. , 5. , 6. , 7. (ii), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 41
Page 50 :
2, , as, ha, n, , Python Functions, , Pr, ak, , 1. What is a function in python?, Ans. A function is a block of organised, reusable code that is used to perform a single, related action. Functions provide, better modularity for your application and a high degree of code reusing., Python gives many built-in functions like print(), etc. but you can also create your own functions. These functions, are called user-defined functions., You can pass data, known as parameters, into a function., A function can return data as a result., , 2. What is the role of indentation in python function., Ans. Indentation (Space) in Python Functions, Python functions don’t have any explicit begin or end like curly braces to indicate the start and stop for the, function, they have to rely on this indentation. It is also necessary that while declaring indentation, you have to, maintain the same indent for the rest of your code., , Br, , ot, , he, , rs, , 3. How to define user define function?, Ans. Defining a Function, You can define functions to provide the required functionality. Here are simple rules to define a function in Python., • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) )., • Any input parameters or arguments should be placed within these parentheses. You can also define parameters, inside these parentheses., • The first statement of a function can be an optional statement - the documentation string of the function or, docstring., • The code block within every function starts with a colon (:) and is indented., • The statement return [expression] exits a function, optionally passing back an expression to the caller., A return statement with no arguments is the same as return None., Syntax, , al, , def functionname( parameters ):, , “function_docstring”, , function_suite, , , return [expression], , oy, , 4. How to call a function in python ? Explain with an example., Ans. Calling a Function: To call a function, use the function name followed by parenthesis., Example:, , G, , def fun():, , print(“Hello”), fun(), , output, , # function calling, , Hello, Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 43
Page 51 :
5. Give the output, , as, ha, n, , def prn():, , print(“****”), print(“hello”), prn(), print(“hi”), prn(), print(“bye”), prn(), , Pr, ak, , Ans. hello, ****, hi, ****, bye, ****, , 6. What is Parameter in python function?, Ans. Information can be passed to functions as parameter. Parameters are specified after the function name, inside the, parentheses. You can add as many parameters as you want, just separate them with a comma., What is the difference between parameter and argument?, Parameters are temporary variable names within functions., The argument can be thought of as the value that is assigned to that temporary variable., For instance, lets consider the following simple function to calculate sum of two numbers., , rs, , 7., Ans., , , , , , return a+b, , sum(10,20), , he, , def sum(a,b):, , ot, , a,b here are the parameter for the function ‘sum’., Arguments are used in procedure calls, i.e. the values passed to the function at run-time.10,20 are the arguments, for the function sum, , Br, , 8. Differentiate between actual parameter(s) and a formal parameter(s) with a suitable example for each. [SP 21], Ans. The list of identifiers used in a function call is called actual parameter(s) whereas the list of parameters used in, the function definition is called formal parameter(s)., Actual parameter may be value/variable or expression.Formal parameter is an identifier., Example:, def area(side): # line 1, , al, , return side*side;, , print(area(5)) # line 2, , oy, , In line 1, side is the formal parameter and in line 2, while invoking area() function, the value 5 is the actual, parameter., A formal parameter, i.e. a parameter, is in the function definition. An actual parameter, i.e. an argument, is in a, function call., , G, , 9. What are the different types of Functions in python?, Ans. There are two basic types of functions: built-in functions and user defined functions., , 44, , (i) The built-in functions are part of the Python language; for instance dir() , len() , or abs() ., (ii) The user defined functions are functions created with the def keyword., Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 52 :
as, ha, n, , 10. Explain the types of function arguments in python, Ans. Function Arguments: You can call a function by using the following types of formal arguments:, • Required arguments , • Keyword arguments, • Default arguments , • Variable number of arguments, • Arguments are passed as a dictionary., (i) Required arguments: Required arguments are the arguments passed to a function in correct positional, order. Here, the number of arguments in the function call should match exactly with the function definition., def show(x,y):, , print(“Name is “,x), , print(“Age is “,y), show(“Raj”,18), , def show(x,y):, , print(“Name is “,x), , print(“Age is “,y), show(y=18,x=”Raj”), , rs, , OUTPUT, Name is Raj, Age is 18, , Pr, ak, , Output:, Name is Raj, Age is 18, (ii) Keyword arguments: Keyword arguments are related to the function calls. When you use keyword, arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to, place argument out of order because the Python interpreter is able to use the keywords provided to match, the values with parameters., , he, , (iii) Default arguments: A default argument is an argument that assumes a default value if a value is not, provided in the function call for that argument. The following example gives an idea on default arguments., def sum(a,b=10):, , print(‘sum is’,a+b), , ot, , , , sum(15,25), sum(15), , Br, , OUTPUT, , sum is 40, sum is 25, , al, , The rule for placing the default arguments in the argument list : Once default value is used for an, argument in function definition, all subsequent arguments to it must have default value. It can also be stated, as default arguments are assigned from right to left., , oy, , (iv) Variable Number of Arguments: In cases where you don’t know the exact number of arguments that you, want to pass to a function, you can use the following syntax with *args:, , The variable stored in *args are represented in the form of tuple., , G, , def change(*a):, , , for i in a:, , , , print(a), , , , print(i), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 45
Page 53 :
change(10,5), , change(15,20,25), , OUTPUT, 10, , as, ha, n, , 5, (10, 5), 15, 20, 25, (15, 20, 25), , Pr, ak, , (v) Arguments are passed as a dictionary (**kwargs): Kwargs allow you to pass keyword arguments to a, function. They are used when you are not sure of the number of keyword arguments that will be passed in, the function. Kwargs can be used for unpacking dictionary key, value pairs. This is done using the double, asterisk notation ( ** )., In the function, we use the double asterisk ** before the parameter name to denote this type of argument., The arguments are passed as a dictionary and these arguments make a dictionary inside function with name, same as the parameter excluding double asterisk **, Example:, def fun(**data):, , print(“\nData type of argument:”,type(data)), , , , for key, value in data.items():, , , , print(data), , , , rs, , , , print(key,value), , he, , fun(Name=”Aman”,Age=18,Marks=56), , , output, , Data type of argument: <class ‘dict’>, , ot, , {‘Name’: ‘Aman’, ‘Age’: 18, ‘Marks’: 56}, Name Aman, Age 18, , Br, , Marks 5, , al, , 11. How does a function return Value?, Ans. If you want to continue to work with the result of your function and try out some operations on it, you will need, to use the return statement to actually return a value., , Example:, , def square(x):, , return x * x, , oy, , , , , , a=5, , print(square(3)), , G, , print(square(a)), , OUTPUT, 9, 25, 46, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 54 :
12. Can a function return multiple values? Explain with an example., Ans. Yes, the return values should be a comma-separated list of values and Python then constructs a tuple and returns, this to the caller,, , Example:, , as, ha, n, , def change(a,b,c,d):, , m=max(a,b,c,d), , n=min(a,b,c,d), , s=a+b+c+d, , return n,m,s, g,h,i=change(2,5,7,20), print (g,h,i), , , OUTPUT, 2 20 34, or, , rs, , Pr, ak, , def change(a,b,c,d):, , m=max(a,b,c,d), , n=min(a,b,c,d), , s=a+b+c+d, , t=(n,m,s), , return t, t1=change(2,5,7,20), print (t1), g,h,i=t1, print(g,h,i), , he, , OUTPUT, (2, 20, 34), 2 20 34, , Br, , ot, , 13. Explain docstrings in python functions?, Ans. Another essential aspect of writing functions in Python: docstrings. Docstrings describe what your function does,, such as the computations it performs or its return values. These descriptions serve as documentation for your, function so that anyone who reads your function’s docstring understands what your function does, without having, to trace through all the code in the function definition., Function docstrings are placed in the immediate line after the function header and are placed in between triple, quotation marks., , oy, , al, , def change(x):, , ‘’’check call by value’’’, , x=[7], , print(x), print(change.__doc__), a=[5,2,3,1], change(a), print(a), , G, , OUTPUT, check call by value, [7], [5, 2, 3, 1], Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 47
Page 55 :
Output: Functions, 14. Give the output, (i) print(“hi”), , 16. Give the output, def sum(a,b):, , , , x=5, , y=10, , sum(x,y), , sum(20,40), , Ans. Output, sum is 15, sum is 60, , 17. Give the output of the following program, , Pr, ak, , def check(a):, , 18. Give the output, , he, , def sum(*a):, , , , , s=s+i, , print(s), , sum(2,3), , sum(2,6,3), , sum(1,2,3,4), , Ans., , , , , OUTPUT, 5, 11, 10, , Output: Default Parameter, abc(a), abc(b), , Ans. output, , a=20, , 50, , b=30, , 80, , abc(a,b), , 90, , 48, , for i in a:, , , , ot, , print(x+y), , s=0, , , , Br, , def abc(x,y=60):, , Ans. OUTPUT, [6, 7, 8, 9], , rs, , 2 [SP 16], , al, , oy, , return a, , print(c), , 19. Give the output, , G, , , , a[i]=a[i]+5, , c=check(b), , i = 9, while i> 1:, if i%2==0:, x = i%2, i = i-1, else:, , i = i-2, x = i, print (x**2), cal(), , , , for i in range(len(a)):, , b=[1,2,3,4], , 15. Give the output, def cal():, , , 49, 25, 9, 1, , , , , Ans. OUTPUT, (i), (ii), (iii), hi, bye, hello, , Ans., , , , , print(“sum is “,a+b), , as, ha, n, , def abc():, , print(“hello”), print(“bye”), abc(), (ii) def abc():, , print(“hello”), print(“hi”), print(“bye”), abc(), (iii) print(“hi”), print(“bye”), def abc():, , print(“hello”), abc(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 56 :
20. Give the output, , 23. Find and write the output of the following Python, code :, 3 [comptt 19], , def abc(a=2,b=4):, , return a+b, x=10, y=20, x=abc(x,y), print(x,y), y=abc(x), print(x,y), x=abc(y), print(x,y), , as, ha, n, , output, 30 20, 30 34, 38 34, , Pr, ak, , Ans., , , , , def Alter(P=15,Q=10):, , P=P*Q, , Q=P/Q, , print (P,”#”,Q), , return Q, A=100, B=200, A=Alter(A,B), print (A,”$”,B), B=Alter(B), print (A,”$”,B), A=Alter(A), print (A,”$”,B), , Ans., , , , , , , 21. Give the output, def abc(x,y=60):, , , a=20, , return x+y, , b=30, , a=abc(a,b), , 24. Find and write the output of the following python, program code:, , rs, , print(a,b), b=abc(a), , print(a,b), , Br, , 22. Give the output, , ot, , print(a,b), , OUTPUT, 50 30, 50 110, 170 110, , def abc(x=50,y=60):, , , a=20, b=30, , return x+y, , al, , b=abc(a,b), print(a,b), , oy, , a=abc(b,a), print(a,b), a=abc(a,b), print(a,b), , G, , Ans., , , , , output, 20 50, 70 50, 120 50, , def Revert(Num,Last=2):, , if Last%2==0:, , Last=Last+1, , else:, , Last=Last-1, , for C in range(1,Last+1):, , Num+=C, , print(Num), A,B=20,4, Revert(A,B), B=B-1, Revert(B), , he, , a=abc(b), , Ans., , , , , 20000 # 100.0, 100.0 $ 200, 2000 # 200.0, 100.0 $ 200.0, 1000.0 # 100.0, 100.0 $ 200.0, , Ans. 35, 9, , 25. Find and write the output of the following python, code:, 3[2019], def Convert(X=45,Y=30):, , X=X+Y, , Y=X-Y, , print (X,”&”,Y), , return X, A=250, B=150, A=Convert(A,B), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 49
Page 57 :
print (A,”&”,B), B=Convert(B), print (A,”&”,B), A=Convert(A), print (A,”&”,B), , 400, 400, 180, 400, 430, 430, , &, &, &, &, &, &, , def Call(P=40,Q=20):, , R=Call(R,S), , print (R,’@’,S), S=Call(S), , Pr, ak, , print(R,’@’,S), , Ans. 300 @ 200, 300 @ 100, 120 @ 100, 300 @ 120, , 29. Find and write the output of the following python, code:, [3][comptt 2020], , rs, , def Assign(P=30,Q=40):, , , , he, , , , P=P+Q, Q=P-Q, , , , Br, , ot, , A=100, , al, , oy, , G, , return P, , S=100, , def Change(P ,Q=30):, , P=P+Q, , Q=P-Q, , print( P,”#”,Q), , return (P), R=150, S=100, R=Change(R,S), print(R,”#”,S), S=Change(S), , 50, , print(P,’@’,Q), , R=200, , 27. Find and write the output of the following python, code:, 3[SP 2020], , Ans. 250 # 150, 250 # 100, 130 # 100, , , , Q=P-Q, , , , def Changer(P,Q=10):, , P=P/Q, , Q=P%Q, , print (P,”#”,Q), , return P, A=200, B=20, A=Changer(A,B), print (A,”$”,B), B=Changer(B), print (A,”$”,B), A=Changer(A), print (A,”$”,B), , 10.0 # 10.0, 10.0 $ 20, 2.0 # 2.0, 10.0 $ 2.0, 1.0 # 1.0, 1.0 $ 2.0, , P=P+Q, , , , 250, 150, 150, 180, 400, 180, , 26. Find and write the output of the following python, code:, 3[2019], , Ans., , , , , , , , , as, ha, n, , Ans., , , , , , , 28. Find and write the output of the following python, code:, [2] [comptt 2020], , print (P, ‘@’,Q), return P, , B=150, , A=Assign(A,B), , print (A, ‘@,B), B=Assign(B), , print (A,’@’,B), , Ans. 250 @ 100, 250 @ 150, 190 @ 150, 250 @ 190, , 30. Give the output, def calc(u):, , , if u%2==0:, , , , else:, , , , , return u+10;, return u+2;, , def pattern(M,B=2):, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 58 :
for CNT in range(0,B):, , , , , , print(), , , , , , print(calc(CNT),M,end=””);, , else:, , def Output(B=2):, , pattern(“*”), , pattern(“#”,4), , , , for T in range (0,B):, , , , print(), , , , pattern(“@”,3), , Ans. OUTPUT, , print(Execute(T),”*”,end=””), , , Output(4), , 10 *3 *, 10 #3 #12 #5 #, , Output(), , 10 @3 @12 @, , Output(3), , Ans. 0 *11 *12 *9 *, , 31. Give the output, , 0 *11 *, , def Execute(M):, , 0 *11 *12 *, , if M%3= =0:, , Pr, ak, , , , return M+10;, , as, ha, n, , , , return M*3, , OUTPUT : Random, 32. What’s the difference between randrange and randint?, Ans. Difference between., randint, , randrange, , rs, , randint(x,y) will return a value >= x and <= y. It will generate randrange(x,y) will return a value >=x and < y. The randrange(start,, a random number from the inclusive range., stop, step) doesn’t include the stop number while generating random, integer, i.e., it is exclusive., , he, , This function takes two parameters. Both are mandatory. The This function takes three parameters(start,stop,step). Out of three, randint (start, stop) includes both start and stop numbers while parameters, two parameters are optional. i.e., start and step are the, generating random integer., optional parameters. The default value of start is 0, if not specified., The default value of the step is 1, if not specified., For example, random.randint(0, 100) will return any random random.randrange(0, 100) will return any random number between, number between 0 to 100 (both inclusive)., 0 to 99. such as 0, 1, 2, …99. It will never select 100., , ot, , 33. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum, values that can be assigned to variable NUMBER., 2 [D 15], , al, , Br, , import random, STRING=”CBSEONLINE”, NUMBER=random.randint(0,3), N=9, while STRING[N]!=”L”:, , print (STRING[N], +STRING[NUMBER] + “#”,end=””), , NUMBER=NUMBER+1, , N=N-1, , ES#NE#IO#, (ii) LE#NO#ON#, ES#NE#IO#, (iv) EC#NB#IS#, Minimum value of NUMBER = 0, Maximum value of NUMBER = 3, , oy, , (i), Ans. (i), , , , (iii) NS#IE#LO#, , (iv) EC#NB#IS#, , G, , 34. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum, values that can be assigned to variable COUNT., 2 [OD 15], , import random, TEXT=”CBSEONLINE”, Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 51
Page 59 :
COUNT=random.randint(0,3), C=9, , , print (TEXT[C] + TEXT[COUNT] + ‘*’,end=””), , , , C=C-1, , , , (i), Ans. (i), , , , COUNT=COUNT+1, , EC*NB*IS*, (ii) NS*IE*LO*, EC*NB*IS*, (iii) ES*NE*IO*, Minimum COUNT = 0, Maximum COUNT = 3, , (iii) ES*NE*IO*, , as, ha, n, , while TEXT[C]!=’L’:, , (iv) LE*NO*ON*, , 35. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum, 2 [comptt 17], values that can be assigned to variable ROUND., import random, , Pr, ak, , PLAY=[40,50,10,20], , ROUND=random.randint(2,3), , for J in range(ROUND,1,-1):, , , print (PLAY[J],”:”,end=””), , (i) 20:10:, Ans. (i) Maximum =3, Minimum =2, , (ii) 20:10:50:, , (iii) 20:, , (iv) 40:50:20:, , rs, , 36. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum, values that can be assigned to variable N., [SP 17], import random, , N=random.randint(1,3), OUT=””, , he, , SIDES=[“EAST”,”WEST”,”NORTH”,”SOUTH”];, , for I in range(N,1,-1):, OUT=OUT+SIDES[I], , print (OUT), , SOUTHNORTH (ii) SOUTHNORTHWEST, SOUTHNORTH, Maximum value of N = 3, Minimum value of N = 1, , (iii) SOUTH, , (iv) EASTWESTNORTH, , Br, , (i), Ans. (i), , , , ot, , , , al, , 37. Observe the following Python code and find out which out of the given options (i) to (iv) are the expected correct, output(s).Also assign the maximum and minimum value that can be assigned to the variable ‘Go’., 2 [SP 16], import random, , oy, , X =[100,75,10,125], , Go = random.randint(0,3), for i in range(Go):, , G, , , , print (X[i],”$$”,end=””), , (i) 100$$75$$10$$, (ii) 75$$10$$125$$, (iii) 75$$10$$, Ans. 100 $$ 75 $$ 10 $$, Minimum Value that can be assigned to Go is 0, Maximum Value that can be assigned to Go is 3, 52, , (iv) 10$$125$$100, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 60 :
38. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum, values that can be assigned to variable N., import random, NUM, , = [“LEFT”,”FRONT”,”RIGHT”,”BACK”], = random.randint(1,3), , NAVG = “”, , for C in range(NUM,1,-1):, , , NAVG = NAVG+NAV[C], , print (NAVG), , as, ha, n, , NAV, , (i) BACKRIGHT, (ii) BACKRIGHTFRONT, (iii) BACK, (iv) LEFTFRONTRIGHT, Ans. (i) BACKRIGHT Max value 3 and minimum value 1 for variable NUM, 39. Observe the following program and answer the questions that follow:, import random, , Pr, ak, , X=3, , N=random.randint(1,X), for i in range(N):, , (a), (b), (i), Ans. (a), , (b), , print (i,”#”,i+1), , What is the minimum and maximum number of times the loop will execute?, Find out, which line of output(s) out of (i) to (iv) will not be expected from the program?, 0#1, (ii) 1#2, (iii) 2#3, (iv) 3#4, Minimum Number = 1, Maximum Number = 3, Line (iv) is not expected to be a part of the output., , rs, , , , [SP 17], , import random, , ot, , X=random.random(), , he, , 40. Study the following program and select the possible output(s) from the options (i) to (iv) following it. Also, write, the maximum and the minimum values that can be assigned to the variable Y., 2 [SP 18], , Y=random.randint(0,4), , print (int(X),”:”,Y+int(X)), , 0: 0, (ii) 1:6, (iii) 2:4, and (iv) are the possible output(s), Minimum value that can be assigned to Y = 0, Maximum value assigned to Y =4, , Br, , (i), Ans. (i), , , , (iv) 0:3, , al, , 41. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum, 2 [D 16], values that can be assigned to variable PICK., import random, , oy, , PICK=random.randint(0,3), , CITY=[“DELHI”,”MUMBAI”,”CHENNAI”,”KOLKATA”], for I in CITY:, , for J in range(1,PICK):, , , , print(), , G, , , , , print(I,end=””), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 53
Page 61 :
(i), , (ii), DELHI, DELHIMUMBAI, DELHIMUMBAICHENNAI, , as, ha, n, , DELHIDELHI, MUMBAIMUMBAI, CHENNAICHENNAI, KOLKATAKOLKATA, (iii), , (iv), , DELHI, MUMBAIMUMBAI, KOLKATAKOLKATAKOLKATA, , DELHI, MUMBAI, CHENNAI, KOLKATA, Ans. Options (i) and (iii) are possible., PICK maxval=3 minval=0, , import random, PICKER=random.randint(0,3), COLOR=[“BLUE”,”PINK”,”GREEN”,”RED”], for I in COLOR:, , for J in range(1,PICKER):, , print(I,end=””), print(), , BLUE, PINK, GREEN, RED, , he, , (i), , rs, , , , Pr, ak, , 42. What are the possible outcome(s) executed from the following code? Also specify the maximum and minimum, values that can be assigned to variable PICKER., , (ii), , BLUE, BLUEPINK, BLUEPINKGREEN BLUE, , (iii), , Br, , ot, , PINK, PINKGREEN, GREENRED, , (iv), BLUEBLUE, PINKPINK, GREENGREEN, REDRED, , Ans. Options (i) and (iv) are possible., PICKER maxval=3 minval=0, , al, , 43. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from, the following code? Also specify the maximum values that can be assigned to each of the variables BEGIN and, LAST., 2 [D 18], , G, , oy, , import random, POINTS=[30,50,20,40,45];, BEGIN=random.randint(1,3), LAST=random.randint(2,4), for C in range(BEGIN,LAST+1):, print (POINTS[C],”#”,end=””), , (i), 20#50#30#, , 54, , (ii), 20#40#45#, , (iii), 50#20#40#, , (iv), 30#50#20#, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 62 :
Ans. (ii) 20#40#45# and (iii) 50#20#40#, Max value for BEGIN 3, , , Max value for LAST 4, , as, ha, n, , 44. What possible output(s) are expected to be displayed on screen at the time of execution of the program from the, following Python code? Also specify the minimum values that can be assigned to each of the variables Start and, End., 2 [comptt 2019], , import random, VAL=[80,70,60,50,40,30,20,10], Start=random.randint(1,3), End=random.randint(Start,4), for I in range(Start,End+1):, , print (VAL[I],”*”,end=””), , (i) 40 * 30 * 20 *, (iii) 50 * 40 * 30 *, Ans. No output, Minimum value for, Minimum value for, , 10 * , , , (ii) 70 * 60 * 50 * 40 * 30 *, (iv) 60 * 50 * 40 * 30 *, , Pr, ak, , , , Start: 1, End : 1, , 35 * 45 * 55 * 65 * 75 *, 15 * 25 * 35 * 45 * , 35 * 45 * 55 *, Minimum value for From:1, Minimum value for To:1, , (ii) 35 * 45 * 55 *, (iv) 35 * 45 * 55 * 65 *, , Br, , (i), (iii), Ans. (ii), , , , print (VAL[I],”*”,), , ot, , , , he, , import random, VAL=[15,25,35,45,55,65,75,85];, From=random.randint(1,3), To =random.randint(From,4), for I in range(From,To+1):, , rs, , 45. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from, the following code? Also specify the minimum values that can be assigned to each of the variables From and To., 2 [2019], , 46. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from, the following code? Also specify the minimum values that can be assigned to each of the variables BEGIN and, LAST., 2[2019], import random, , al, , VALUES=[10,20,30,40,50,60,70,80];, BEGIN=random.randint(1,3), , oy, , LAST =random.randint(BEGIN,4), , for I in range(BEGIN,LAST+1):, , , G, , (i), (iii), Ans. (i), , , , print (VALUES[I],”-”,end=””), , 30 - 40 - 50 - , 30 - 40 - 50 - 60 - , 30-40-50Minimum value for BEGIN:1, Minimum value for LAST:1, , (ii) 10 - 20 - 30 - 40 (iv) 30 - 40 - 50 - 60 - 70 –, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 55
Page 63 :
47. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from, the following code? Also specify the maximum values that can be assigned to each of the variables FROM and, TO., 2 [SP 2019-20], AR=[20,30,40,50,60,70];, FROM=random.randint(1,3), TO=random.randint(2,4) 2 3 4, for K in range(FROM,TO+1):, , , print (AR[K],end=”# “), , (i) 10#40#70#, Ans. (ii) 30#40#50#, , (ii) 30#40#50#, (iii) 50#60#70#, Maximum value FROM,TO is 3,4, , as, ha, n, , import random, , (iv) 40#50#70#, , import random, AR=[20,30,40,50,60,70];, Lower =random.randint(1,3), Upper =random.randint(2,4), , , print (AR[K],end=”#“), , (i) 10#40#70#, , (ii) 30#40#50#, , (iii) 50#60#70#, , (iv) 40#50#70#, , he, , Ans. OUTPUT: (ii), , rs, , for K in range(Lower, Upper +1):, , Pr, ak, , 48. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from, the following code? Also specify the maximum values that can be assigned to each of the variables Lower and, Upper., , Maximum value of Lower: 3, Maximum value of Upper: 4, , Br, , import random, , ot, , 49. What possible output(s) are expected to be displayed on screen at the time of exection of the program from, the following code? Also specify the minimum and maximum values that can be assigned to the variable End., [comptt 2020], Colours=[“VIOLET”,”INDIGO”,”BLUE”,”GREEN”,”YELLOW”,”ORANGE”,”RED”], End=random.randrange(2)+3, , Begin=random.randrange(End)+1, , al, , for i in range(Begin,End):, print(Colours[i],end=’&’), , oy, , , , (i) INDIGO&BLUE&GREEN&, , (ii) VIOLET&INDIGO&BLUE&, , (iii) BLUE&GREEN&YELLOW&, , (iv) GREEN&YELLOW&ORANGE&, , G, , Ans. (i) INDIGO&BLUE&GREEN&, Minimum Value of End = 3, Maximum Value of End = 4, 56, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 67 : p=p+s[i], , print(“Changed String”,p), str=”SUCCESS”, print(“Original String”,str), repch(str);, , n=ord(Name[x]), n=n-1, N=N+chr(n), , Ans. AOROoILE, , [SP 21], , 67. Give the output, , def Display(str):, m=””, , for i in range(0,len(str)):, , if(str[i].isupper()):, , m=m+str[i].lower(), , elif str[i].islower():, , m=m+str[i].upper(), , else:, , if i%2==0:, , m=m+str[i-1], , else:, , m=m+”#”, , print(m), Display(‘
[email protected]’), , Ans. fUN#pYTHONn#., , 2 [SP 2019-20], , 70. Find the output of the following program :, , def MIXITNOW(S):, , WS=””, , for I in range(0,len(S)-1,2):, , WS=WS+S[I+1], , WS=WS+S[I], , S=WS, , print(S), , WS=””, , for I in range(0,len(S)):, , if S[I]>=”M” and S[I]<=”U”:, , WS=WS+”@”;, , else:, , WS=WS+S[I-1:I], , print(WS), Word=”CRACKAJACK”;, MIXITNOW(Word);, , rs, , 68. Give the output, , Ans. Original String SUCCESS, Hello, Changed String SU!CE@, , as, ha, n, , else:, , Pr, ak, , , , , Name=N, print(Name), , Ans. RCCAAKAJKC, @RCCAAKAJK, , Br, , ot, , he, , def fun(s):, , k=len(s), , m=” “, , for i in range(0,k):, , if(s[i].isupper()):, , m=m+s[i].lower(), , elif s[i].isalpha():, , m=m+s[i].upper(), , else:, , m=m+’bb’, , print(m), fun(‘school2@com’), , al, , Ans. SCHOOLbbbbCOM, 69. Give the output, , G, , oy, , def repch(s):, , p=””, , for i in range(len(s)-1):, , if i%2!=0 and s[i]==s[i+1]:, , p=p+”@”, , print(“Hello”), , elif s[i]= =s[i+1]:, , p=p+”!”, , else:, 60, , 71. Find the output of the following program :, , def JumbleUp(T):, , CT=””, , L=len(T), , for C in range(0,L,2):, , CT=CT+T[C+1], , CT=CT+T[C], , T=CT, , CT=””, , print(T), , for C in range(1,len(T),2):, , if “U”>=T[C]>=”M”:, , #if T[C]>=”M” and T[C]<=”U”:, , CT=CT+”@”, , else:, , CT=CT+T[C-1:C+1], , print(CT), Str=”HARMONIOUS”, JumbleUp(Str), , Ans. AHMRNOOISU, AH@@OI@, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 68 :
W=W+Big(WX[i],WX[i+1]), W=W+WX[L-1], print(W), , Ans. zyom, , 73. Give the output, , as, ha, n, , 72. Find the output of the following program :, , def Big(A,B):, , if (A>B):, , return chr(ord(A)+1), , else:, , return chr(ord(B)+2), WX=”Exam”, W=””, L=len(WX), for i in range(0,L-1,1):, , a=”Hello”, L=list(a), a=’’.join(reversed(L)), print(a), , Ans. olle, , Output : Global Variable, , 76. Give the output, , def fun():, , , print(a), a=5, fun(), print(a), , he, , rs, , 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 the function or in, global scope is known as global variable., This means, global variable can be accessed inside, or outside of the function where as local variable can, be used only inside of the function. We can access, by declaring variable as global A., , Inside add() : 12, In main: 15, Note: In case you have a local variable with the same, name, use the globals() function to access global, variable., globals()[‘your_global_var’], for ex:, , y=globals()[‘a’], , Pr, ak, , 74. 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., [SP 2019-20], , Br, , ot, , 75. Explain the use of global key word used in a function, with the help of a suitable example., [SP 21], Ans. Use of global key word: In Python, global keyword, allows the programmer to modify the variable outside, the current scope. It is used to create a global variable, and make changes to the variable in local context., A variable declared inside a function is by default, local and a variable declared outside the function, is global by default. The keyword global is written, inside the function to use its global value. Outside, the function, global keyword has no effect., , Example:, , G, , oy, , al, , c = 10, # global variable, def add():, , global c, , c = c + 2, # global value of c is incremented, by 2, , print(“Inside add():”, c), add(), c=15, print(“In main:”, c), , output:, , Ans. 5, 5, , 77. Give the output, , , def fun():, , , a=10, , print(a), a=5, fun(), print(a), , Ans. 10, 5, , 78. Give the output, , def fun():, , global a, , a=10, , print(a), a=5, fun(), print(a), , Ans. 10, 10, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 61
Page 69 :
79. Give the output, def fun():, , , 83. Find and write the output of the following python, [SP 2019-20], code:, , , a=20, , print(a), def fun2():, , global a, , a=30, , print(a), a=10, fun(), print(a), fun2(), print(a), , Ans. 15, , 84. Write the output of the following Python code:, [1][comptt 2020], , Ans. OUTPUT, 20, 10, 30, 30, 80. Give the output, def fun(a):, , , Pr, ak, , def Update(X=10):, , X += 15, , print( ‘X = ‘, X), X=20, Update(), print( ‘X = ‘, X), , Ans. X = 25, X = 20, , , a=10, , print(a), a=5, fun(a), print(a), , 85. Give the output, def fun():, , , he, , Br, , ot, , global a, , a=10, , y=a, , print(“inside”,a), , print(“y=”,y), a=5, fun(), print(“outside”,a), , al, , G, , oy, , , a=10, , y=a, , print(“inside”,a), , print(“y=”,y), a=5, fun(), print(“outside”,a), , Ans. inside 10, y=10, outside 5, 62, , , a=10, , y=globals()[‘a’], , print(“inside”,a), , print(“y=”,y), a=5, fun(), print(“outside”,a), , rs, , Ans. 10, 5, 81. Give the output, , def fun():, , Ans. inside 10, y=10, outside 10, 82. Give the output, , def fun():, , as, ha, n, , a=10, def call():, , global a, , a=15, , b=20, , print(a), call(), , Ans. inside 10, y=5, outside 5, , 86. Give the output, def func(x,y=2):, , , , g=5, , x=x-y;, , g=g*10;, , print(x,y,g), g=7, h=10, func(g,h), print(g,h), func(g), , , Ans., , , , , print(g,h), -3 10 50, 7 10, 5 2 50, 7 10, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 70 :
Ans. 3 8 13, 8 5, 8 13 18, , as, ha, n, , demo(a,b), print(a,b), demo(a,b), , 87. Give the output, , g=10, def func(x,y=10):, , x=x-y, , y=x*10, , z=x+y+g, , return z, g=func(g,15), print(g), g=func(g), print(g), , 89. Give the output, def pa(a,b,c):, , , , x=4;, , c+=x;, , c*=globals()[‘x’], , b+=c;, , return a,b,c, y=1, x=2, z=5, x,y,z=pa(y,x,z), print(x,y,z), y,z,x=pa(z,y,x), print(x,y,z), , Ans. -45, -650, , Pr, ak, , 88. Give the output, a=3, , , def demo(x,y):, , global a, , a=x+y, , z=a+y, , y+=x, , print(x,y,z), b=5, , rs, , Ans. 1 20 18, 5 18 25, , Functions/Methods/Modules Name, , he, , Math Module, Function, ceil(x), , Returns the smallest integer greater than or equal to x., Returns the absolute value of x, , ot, , fabs(x), factorial(x), , Returns the factorial of x, , isnan(x), trunc(x), exp(x), , Returns the largest integer less than or equal to x, Returns the remainder when x is divided by y, , Br, , floor(x), fmod(x, y), , Description, , Returns True if x is a NaN, Returns the truncated integer value of x, Returns e**x, Returns the base-10 logarithm of x, , pow(x, y), , Returns x raised to the power y, , sqrt(x), , Returns the square root of x, , oy, , al, , log10(x), , Returns the cosine of x, , sin(x), , Returns the sine of x, , tan(x), , Returns the tangent of x, , degrees(x), , Converts angle x from radians to degrees, , pi, , Mathematical constant, the ratio of circumference of a circle to it’s diameter (3.14159...), , e, , Mathematical constant e (2.71828..., , G, , cos(x), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 63
Page 71 :
random module, randint(), , random(), , randrange(), , uniform(), , pickle module, load(), , csv module, Dictreadwe(), , DictWriter(), , reader(), , writer(), , Matplotlib.pyplot, axes(), , ba(), , bath(), , plot(), , show(), , title(), , xlabel(), , ylabel(), , statistics module, mean(), , median, , as, ha, n, , dump(), , model(), , pie(), , Pr, ak, , 90. Name the Python Library modules which need to be imported to invoke the following functions:, (i) ceil(), (ii) randint(), Ans. (i) math, (ii) random, , [D 17], , 91. Observe the following Python functions and write the name(s) of the module(s) to which they belong:, , (i) uniform(), (ii) findall(), 1 [SP 16], Ans. (i) random, (ii) re, , rs, , 92. Name the Python Library modules which need to be imported to invoke the following functions:, (i) ceil(), (ii) randint() , (ii) random, Ans. (i) math, 1 [OD 17], , 94. Identify and write the name of the module to which the following functions belong:, (i) ceil( ), (ii) findall(), , Ans. (i) ceil( ) - math module (ii) findall( ) – re module, , 1 [SP 18], , 95. Name the Python Library modules which need to be imported to invoke the following functions, , (i) load(), (ii) pow(), Ans. (i) pickle, (ii) math, , 1 [D 16], , Br, , ot, , he, , 93. Name the Python Library modules which need to be imported to invoke the following functions, (i) floor(), (ii) randint(), , (ii) random, Ans. (i) math, , al, , 96. Name the Python Library modules which need to be imported to invoke the following functions (i) sqrt() (ii), dump(), 1 [OD 16], Ans. (i) math, (ii) pickle, 1 [D 18], , oy, , 97. Name the Python Library modules which need to be imported to invoke the following functions:, (i) sin(), (ii) search(), Ans. (i) math, (ii) re, , G, , 98. Name the function/method required to (i) check if a string contains only uppercase letters and (ii) gives the total, length of the list., 1 [D 15], (ii) len(), Ans. (i) isupper(), , 99. Name the function/method required to (i) check if a string contains only alphabets and (ii) give the total length, of the list., 1 [OD 15], Ans. isalpha() len(), 64, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 72 :
100. Name the Python Library modules which need to be imported to invoke the following functions : 1 [comptt 2019], (i) open(), (ii) factorial(), Ans. (i) os, (ii) math, 1[2019], , as, ha, n, , 101. Name the Python Library modules which need to be imported to invoke the following functions:, (i) search(), (ii) date(), (ii) datetime, Ans. (i) re, , 102. Name the Python Library modules which need to be imported to invoke the following functions:, (i) sqrt(), (ii) start (), Ans. (i) math, (ii) re, , 1 [2019], , 103. Name the Python Library modules which need to be imported to invoke the following functions: 1 [comptt 2020], (i) cos(), (ii) randint() , Ans. (i) math, (ii) random, , Pr, ak, , 104. Name the Python Library modules which need to be imported to invoke the following functions: [1][comptt 2020], (i) floor(), (ii) random(), Ans. (i) math, (ii) random, 105. Name the Python Library modules which need to be imported to invoke the following functions:, (i) sin( ), (ii) randint ( ), , 1[SP 2020], Ans. (i) math, (ii) random, 106. Name the built-in mathematical function/method that is used to return an absolute value of a number., , G, , oy, , al, , Br, , ot, , he, , rs, , Ans. abs(), , 1[SP 21], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 65
Page 74 :
3, , as, ha, n, , File Handling, , File is a named location on disk to store related information. It is used to permanently store data in a non-volatile, memory (e.g. hard disk). There are three types of files that can be handled in python, normal text files, binary files, (written in binary language, 0s and 1s) and CSV files., Access, , Modes Description, , r, , Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default, mode. Gives error if file does not exist., , 2, , rb, , Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file., This is the default mode., , 3, , r+, , Opens a file for both reading and writing. The file pointer placed at the beginning of the file., , 4, , rb+, , Opens a file for both reading and writing in binary format. The file pointer placed at the beginning, of the file., , 5, , w, , Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a, new file for writing., , 6, , wb, , Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does, not exist, creates a new file for writing., , 7, , w+, , Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does, not exist, creates a new file for reading and writing., , 8, , wb+, , Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists., If the file does not exist, creates a new file for reading and writing., , 9, , a, , Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file, is in the append mode. If the file does not exist, it creates a new file for writing., , 10, , ab, , 11, , a+, , Br, , ot, , he, , rs, , Pr, ak, , 1, , Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists., That is, the file is in the append mode. If the file does not exist, it creates a new file for writing., , al, , Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists., The file opens in the append mode. If the file does not exist, it creates a new file for reading and, writing., , ab+, , Opens a file for both appending and reading in binary format. The file pointer is at the end of the, file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new, file for reading and writing., , oy, , 12, , Text File, , G, , Text files are structured as a sequence of lines, where each line includes a sequence of characters., Each line is terminated with a special character, called the EOL or End of Line character. There are several types, but, the most common is the comma {,} or newline character. It ends the current line and tells the interpreter a new one, has begun., Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 67
Page 75 :
In Python, a file operation takes place in the following order., (i) Open a file , , (ii) Read or write (perform operation) , , (iii) Close the file, , file_object, , where, , as, ha, n, , Open a file, To open the file, use the built-in open() function., The open() function returns a file object, it is used to read or modify the file accordingly, Syntax, = open(“filename”, “mode”), , file_object is the variable to add the file object., , Pr, ak, , Filename is the name of file, Mode(optional) tells which way the file will be used., We specify whether we want to read ‘r’, write ‘w’ or append ‘a’ to the file. We also specify if we want to open the, file in text mode or binary mode. The default is reading in text mode. In this mode, we get strings when reading from, the file., for example:, f=open(“abc.txt”,”w”), , rs, , where, f is the object of file, “abc.txt” is the name of file, “w” is the mode, , … . . .. . . ., , f.close(), , ot, , f=open(“abc.txt”,”w”), , he, , Closing a file, close() function closes the file and frees the memory space acquired by that file., You should always close your files, as in some cases, due to buffering, changes made to a file may not show until you, close the file., , Br, , With statement, The with statement will automatically close the file after the nested block of code., with open(“filename”) as file:, do something with data, , al, , with open(‘abc.txt’, ‘w’) as f:, f.write(‘Hi there!’), , oy, , Writing in file, There are two ways to write in a file., (i) write() : Inserts the string str1 in a single line in the text file., , G, , File_object.write(str1), , (ii) writelines() : For a list of string elements, each string is inserted in the text file. Used to insert multiple strings, at a single time., , File_object.writelines(L) for L = [str1, str2, str3], 68, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 76 :
1. Differentiate between “w” and “r” file modes used in Python while opening a data file. Illustrate the difference, using suitable examples., [2][comptt 2020], Ans. A file is opened using “w” mode to write content into the file., A file is opened using “r” mode to read content from the file., Example:, , , file=open(‘NOTES.TXT’,’w’), , , , file.write(S), , , , , as, ha, n, , def Create():, , S=”This is a sample”, file.close(), , def Read():, , , file=open(‘NOTES.TXT’,’r’), , , , print(Lines), , , , Lines=file.readline();, , Pr, ak, , , , file.close(), , Create();, Read();, , Using write function, , 2. Write a prgram to create a text file “abc.txt” and store some data into file., Ans. f=open(‘abc.txt’,”w”), , rs, , f.write(“sunday”), f.write(“monday”), , f.write(“tuesday”), , he, , f.close(), , or, , with open(‘abc.txt’,”w”) as f:, , , , f.write(“sunday”), , , , f.write(“tuesday”), , f.write(“monday”), , Br, , #Reading file, , ot, , , , e=open(“abc.txt”), l=e.read(), , # or e=open(“abc.txt”,”r”), , print(l), , e.close(), , al, , , OUTPUT, , sundaymondaytuesday, , oy, , As you can see, the output is displayed on single line, to get it on next line put ‘\n at the end of the line., 3. Modify the above prog and put ‘\n’ at the end of line., f=open(“abc.txt”,”w”), , G, , f.write(“sunday\n”), f.write(“monday\n”), , f.write(“tuesday\n”), f.close(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 69
Page 77 :
# or e=open(“abc.txt”,”r”), , Ans. OUTPUT:, sunday, monday, tuesday, , Using writelines(), 4. Write a program to create a file and store data into file using writelines(), , Pr, ak, , with open(‘abc.txt’,”w”) as f:, , L=[“sunday\n”,”monday\n”,”tuesday\n”], , f.writelines(L), # or open(“abc.txt”,”r”), with open(“abc.txt”) as e:, , g=e.read(), , print(g), , as, ha, n, , e=open(“abc.txt”), l=e.read(), print(l), e.close(), , Ans. OUTPUT, sunday, monday, tuesday, , Reading from text file, , he, , rs, , Using Read() function, File_object.read([n]), Read n no of bytes and returns it in form of a string. if n is not specified, reads the entire file., 5. Write a program to read a text file “abc.text” using read(), # or open(“abc.txt”,”r”), , ot, , with open(“abc.txt”) as e:, , g=e.read(), , print(g), , or, , Br, , e=open(“abc.txt”,”r”), l=e.read(), print(l), e.close(), , al, , Ans. OUTPUT, sunday, monday, tuesday, , oy, , 6. Write a program to read the text file “abc.txt” and return the 10 first characters of the file:, , G, , e=open(“abc.txt”,”r”), l=e.read(10), print(l), e.close(), , Ans. OUTPUT, sunday, mon, 70, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 78 :
Using readline(), , 7. Write a program to read 1st line from “abc.txt” and display on screen., e=open(“abc.txt”,”r”), , l=e.readline(), print(l), , e.close(), , Ans. OUTPUT, sunday, , with open(“abc.txt”,”w”) as f:, , , , , Pr, ak, , 8. Give the output of the following program, , as, ha, n, , Reads a line of the file and returns in form of a string., If n is given, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line., File_object.readline([n]), , L=[“sunday\n”,”monday\n”,”tuesday\n”], f.writelines(L), , e=open(“abc.txt”,”r”), l=e.readline(10), print(l), , e.close(), , rs, , Ans. Output, sunday, , l=e.readline(), while(l):, , , print(l,end=””), l=e.readline(), , ot, , , , he, , 9. Modify the above program and read entire file using readline function, Ans. e=open(‘abc.txt’,’r’), , e.close(), , Br, , Using Readlines(), Reads all the lines and return them as each line a string element in a list., File_object.readlines(), , al, , 10. Write a program to read text file “abc.text” using readlines function, , with open(“abc.txt”,”r”) as e:, , , print(l), , oy, , , , l=e.readlines(), , Ans. OUTPUT, [‘sunday\n’, ‘monday\n’, ‘tuesday’], , G, , 11. Modify the above program and print the list using for loop, with open(“abc.txt”,”r”) as e:, , , , , , l=e.readlines(), for i in l:, , print(i), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 71
Page 79 :
or, with open(“abc.txt”,”r”) as e:, , , , for i in e:, , Ans. OUTPUT, sunday , , print(i), , monday, , , tuesday, , as, ha, n, , , , As shown in output, next line is printing after skipping two lines, the reason behind it is the lines in file itself has a, newline character ‘\n’. print() also has a new line character (“\n”).To avoid two newlines when printing, give the end, parameter in print statement., 12. Modify the above program by adding end parameter in print statement, with open(“abc.txt”,”r”) as e:, , , , , l=e.readlines(), , Pr, ak, , , , for i in l:, , print(i,end=””), , Ans. Output, sunday, monday, tuesday, , def read_file():, f = open(‘story., txt’, ‘r’), i=f.readlines(), for line in i:, print (line,end=””), f.close(), , Br, , ot, , def read_file():, f = open(‘story., txt’, ‘r’), for i in f:, print (i,end=””), f.close(), , 2nd Method, , he, , 1st Method, , rs, , 13. Write a method in python to read the content from a text file story.txt line by line and display the same on screen., 2 [OD 15], Ans., 3rd Method, def read_file():, with open(“story.txt”,”r”), as f:, i=f.readline(), while i:, print(i,end=””), i=f.readline(), , oy, , al, , 14. Write a program in Python to read lines from a text file NOTES.TXT, count and print those lines, which are, ending with ‘.’ or ‘,’, For eg. if the file contains :, In Python, a file operation takes place in the following order:, (i) Open a file., (ii) Read or write,, (iii) Close the file., output : count=3, Ans. c=0, with open(“NOTES.TXT “,”r”) as e:, , G, , , , , , , 72, , for i in e:, , if i[len(i)-2]==’.’ or i[len(i)-2]==’,’ :, , c=c+1, print(“count=”,c), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 80 :
15. Write a method in Python to read lines from a text file DIARY.TXT, and display those lines, which are starting, with an alphabet ‘P’., 2[SP 17], Ans., 1st Method, , 2nd Method, , 3rd Method, , as, ha, n, , def display():, def display():, def display():, file=open(‘DIARY., file=open(‘DIARY., with open(“DIARY.TXT”,”r”), TXT’,’r’), TXT’,’r’), as e:, line=file.readline(), l=file.readlines(), for i in e:, while line:, for line in l:, if i[0]= =’P’ :, if line[0]= =’P’ :, if line[0]= =’P’ :, print(i), print (line), print (line), line=file.readfile.close(), line(), file.close(), , 1st Method, , rs, , Pr, ak, , 16. Write a user defined function in Python that displays the number of lines starting with ‘H’ in the file Para.txt.Eg:, 2, if the file contains:, Whose woods these are I think I know., His house is in the village though;, He will not see me stopping here, To watch his woods fill up with snow., Then the line count should be 2., , [SP 16], Ans., def countH():, c=0, f=open(‘Para.txt’), for i in f:, if i[0]==’H’:, c=c+1, print(“no of lines are “,c), f.close(), , Br, , ot, , he, , def countH():, f = open (“Para.txt”, “r”), count =0, l=f.readlines(), for i in l:, if i[0]==’H’:, count+=1, print (“no. of lines are”,count), f.close(), , 2nd Method, , 17. Write a function in python to count the number of lines in a text file ‘STORY.TXT’ which is starting with an, alphabet ‘A’ or “a”, [SP 2019-20], Ans., , al, , 1st Method, , G, , oy, , def COUNTLINES():, c=0, f=open(‘STORY.TXT’), l=f.readlines(), for i in l:, if i[0]==’A’ or i[0]= =’a’:, #or if i[0] in [“A”,”a’], c=c+1, print(“Total lines “,c), f.close(), , 2nd Method, def COUNTLINES():, c=0, f=open(‘STORY.TXT’), l=f.readline(), while l:, if l[0]==’A’ or I[0]==’a’:, c=c+1, l=f.readline(), print(“Total lines “,c), f.close(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 73
Page 81 :
18. Write a method/function ABLINES() in python to read contents from a text file LINES.TXT, to display those, lines, which are either starting with an alphabet ‘A’ or starting with alphabet ‘B’., For example:, If the content of the file is___________________________________________________________________, , as, ha, n, , A BOY IS PLAYING OUTSIDE, THE PLAYGROUND IS BIG, BANYAN TREE IS IN THE GROUND, , __________________________________________________________________, The method/function should display, A BOY IS PLAYING OUTSIDE, BANYAN TREE IS IN THE GROUND, , , , , , file=open(‘LINES.TXT’,’r’), , , , for w in lines:, , , , , , , lines = file.readlines(), , Pr, ak, , Ans. def ABLINES():, , if w[0]= =”A” or w[0]= =”B”:, print (w), , file.close(), , 2[2019], , # or w[0] in [“A”,”B”], , rs, , 19. Write a method/function AEDISP() in python to read lines from a text file WRITER.TXT, and display those lines,, which are starting either with A or starting with E., For example:, If the content of the file is, , he, , __________________________________________, , A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH., WE SHOULD TAKE CARE OF OUR ENVIRONMENT., EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD., , ot, , __________________________________________, The method should display, , Br, , A CLEAN ENVIRONMENT IS NECESSARY FOR OUR GOOD HEALTH., EDUCATIONAL INSTITUTIONS SHOULD TAKE THE LEAD., , , , 2[2019], , Ans. def AEDISP():, , , , lines = file.readlines(), , al, , , , file=open(‘WRITER.TXT’,’r’), , , , oy, , , , for w in lines:, , , , , if w[0]==”A” or w[0]==”E”:, print (w), , file.close(), , G, , 20. Write a program to count no of words in text file ”abc.txt”., Ans. f=open(‘abc.txt’,”w”), f.write(“In Python, \n a file operation takes place in the following order.”), f.close(), 74, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 82 :
2nd Method, , c=0, with open(“abc.txt”,”r”), as e:, for i in e:, k=i.split(), for j in k:, c=c+1, print(c), , c=0, with open(“abc.txt”,”r”)as, e:, i=e.read(), k=i.split(), for j in k:, c=c+1, print(c), , Output:, 11, , 21. A text file “Quotes.Txt” has the following data written in it:, Living a life you can be proud of, , f=open(‘abc.txt’), i=f.read(), k=i.split(), print(len(k)), , 2 [SP 17], , Pr, ak, , Doing your best, , 3rd Method, , as, ha, n, , 1st Method, , Spending your time with people and activities that are important to you, Standing up for things that are right even when it’s hard, Becoming the best version of you, , Write a user defined function to display the total number of words present in the file., Ans. def countwords():, , , S=open(“Quotes.Txt”,”r”), , , , z=f.split(), , , , count=0, , for i in z:, , count=count+1, , , , , rs, , , , f=S.read(), , S.close(), , he, , , , print (“Total number of words”,count), , ot, , 22. Observe the following code and answer the questions that follow:, File = open(“Mydata”,”a”), , Br, , _____________________ #Blank1, File.close(), , (i) What type (Text/Binary) of file is Mydata?, (ii) Fill the Blank 1 with statement to write “ABC” in the file “Mydata”, , 1[SP 17], , (ii) File.write(“ABC”), , al, , Ans. (i) Text File, , , , oy, , 23. Write a method/function SHORTWORDS() in python to read lines from a text file WORDBANK.TXT and display, those words, which are lesser than 5 characters., For example:, If the content of the file is, , G, , _________________________________________, HAPPY JOY WELCOME KITE, LOVELY POSITIVE FUN, _________________________________________, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 75
Page 83 :
The method/function should display, JOY, KITE, FUN, , , , , , c=0, , , , file=open(‘WORKBANK.TXT’,’r’), , , , line = file.read(), , , , word = line.split(), , , , for w in word:, , , , if len(w)<5:, print (w), file.close(), , Pr, ak, , , , , as, ha, n, , Ans. def SHORTWORDS():, , 2[2019], , 24. Write a method/function ISTOUPCOUNT() in python to read contents from a text file WRITER.TXT, to count, and display the occurrence of the word “IS” or “TO” or “UP”., For example:, If the content of the file is, __________________________________________, , rs, , IT IS UP TO US TO TAKE CARE OF OUR SURROUNDING. IT IS NOT, , POSSIBLE ONLY FOR THE GOVERNMENT TO TAKE RESPONSIBILITY, _________________________________________, , he, , The method/function should display, Count of IS TO and UP is 6, Ans., , ot, , 1st Method, , oy, , al, , Br, , def ISTOUPCOUNT():, c=0, file=open(‘WRITER.TXT’,’r’), line = file.read(), word = line.split(), for w in word:, if w==”IS” or w==”TO” or, w==”UP”:, # or w in [“IS”,”TO”,”UP”], c=c+1, print (“Count of IS TO and UP, is “,c), file.close(), , 2nd Method, , 3rd Method, , def ISTOUPCOUNT():, def ISTOUPCOUNT():, d=0, d=0, f=open(‘WRITER., file=open(‘WRITER., TXT’), TXT’,’r’), l=f.readlines(), i = file.read(), for i in l:, k=i.split(), k=i.split(), a=k.count(“IS”), a=k.count(“IS”), b=k.count(“TO”), b=k.count(“TO”), c=k.count(“UP”), c=k.count(“UP”), d=a+b+c, d=d+a+b+c, print(Count of IS TO, print(Count of IS, and UP is “,d), TO and UP is”,d), f.close(), f.close(), , G, , 25. Write a function countmy( )in Python to read the text file “DATA.TXT” and count the number of times “my” occurs, in the file. For example if the file “DATA.TXT” contains: “This is my website. I have displayed my preferences, in the CHOICE section.” The countmy( ) function should display the output as, [SP 18], “my occurs 2 times”, , 76, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 84 :
Ans., 2nd Method, , def countmy():, c=0, file=open(‘DATA., TXT’,’r’), line = file.read(), word = line.split(), for w in word:, if w==”my”:, c=c+1, print (“my occurs, “,c,”times”), file.close(), , def countmy():, d=0, f=open(‘DATA.TXT’), l=f.readlines(), for i in l:, k=i.split(), a=k.count(“my”), d=d+a, print(“my occurs”,d,”times”), f.close(), , 3rd Method, def countmy():, f=open(“DATA.TXT”,”r”), k=f.read(), p=k.split(), c=p.count(“my”), print(“my occurs”,c,”times”), f.close(), , as, ha, n, , 1st Method, , rs, , num=0, f=open(“story.txt”,”rt”), N=f.read(), M=N.split(), for x in M:, if x==”Me” or x== “My”:, num=num+1, f.close(), print(“Count of Me/My in file:”,num), , he, , , , , , , , , , , , Pr, ak, , 26. Write a function in Python that counts the number of “Me” or “My” words present in a text file “STORY.TXT”., [SP 21], If the “STORY.TXT” contents are as follows:, My first book was Me and My Family., It gave me chance to be Known to the world., The output of the function should be:, Count of Me/My in file: 4, Ans. def displayMeMy():, , al, , Br, , ot, , 27. Write a method/function BIGWORDS() in Python to read contents from a text file CODE.TXT, to count and, display the occurrence of those words, which are having 5 or more alphabets., 2 [comptt 19], For example :, If the content of the file is, ME AND MY FRIENDS, ENSURE SAFETY AND SECURITY OF EVERYONE, The method/function should display, Count of big words is 5, Ans., 1st Method, , G, , oy, , def BIGWORDS():, f=open(‘CODE.TXT’), c=0, line = f.read(), word = line.split(), for w in word:, , if len(w)>=5:, , c=c+1, f.close(), print(“Count of big words is”,c), , 2nd Method, def BIGWORDS():, f=open(‘CODE.TXT’), c=0, for line in f:, word = line.split(), for w in word:, if len(w)>=5:, c=c+1, f.close(), print(“Count of big words is”,c), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 77
Page 85 :
c=0, , , , file=open(“STORY.TXT”,”r”), , , , line = file.read(), , , , word = line.split(), , , , for w in word:, , , , if len(w)<4:, , , , print( w), , , , file.close(), , Pr, ak, , 29. Write a program to COUNT NO OF “IN”(ANY CASE), Ans. f=open(‘abc.txt’,”w”), , as, ha, n, , 28. Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and display, those words, which are less than 4 characters., [SP 2019-20], Ans. def DISPLAYWORDS():, , f.write(“In Python, \n a file operation takes place in the following order.”), f.close(), c=0, with open(“abc.txt”,”r”)as e:, for i in e:, , , , k=i.split(), , , , for j in k:, , , , if j.upper()==”IN”:, c=c+1, , he, , , , , rs, , , , print(c), , Br, , ot, , 30. Write a method in python to read lines from a text file INDIA.TXT, to find and display the occurrence of the, word “India”. For example: If the content of the file is “India is the fastest growing economy. India is looking for, more investments around the globe. The whole world is looking at India as a great market. Most of the Indians, can foresee the heights that India is capable of reaching.” ____, The output should be 4, , 2[D 18], Ans., 1st Method, , G, , oy, , al, , def display():, c=0, file=open(‘INDIA., TXT’,’r’), for LINE in file:, Words = LINE.split(), for W in Words:, , if W==”India”:, , c=c+1, print (c), file.close(), , 78, , 2nd Method, def display():, c=0, file=open(‘INDIA., TXT’,’r’), lines = file.readline(), while lines:, words = lines.split(), for w in words:, if w= =”India”:, c=c+1, lines = file., readline(), print (c ), file.close(), , 3rd Method, def display():, f=open(“INDIA.TXT”,”r”), k=f.read(), l=k.split(), print(l.count(“India”)), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 86 :
Write a program to count the no of alphabets in text file “abc.txt”., with open(‘abc.txt’,”w”) as f:, L=(“sunday\n”,”monday\n”,”tuesday\n”), f.writelines(L), 1st Method, , 2nd Method, , c=0, with open(“abc.txt”,”r”), as e:, for i in e:, for j in i:, if j.isalpha():, c=c+1, print(c), , p=open(“abc.txt”,”r”), k=p.read(), count=0, for i in k:, if i.isalpha():, count+=1, print(count), p.close(), , f=open(“C:\\abc.txt”), k=f.read(), c=0, for i in k:, if i.isalpha():, c=c+1, print(c), , Pr, ak, , output:, 19, , 3rd Method, , as, ha, n, , 31., Ans., , , , , , he, , p=open(“abc.txt”,”r”), k=p.readlines(), for i in k:, if len(i)>20:, print(i), , ot, , , , , , , , rs, , 32. Write a method/function BIGLINES() in Python to read lines from a text file CONTENT.TXT, and display those, 2 [comptt 19], lines, which are bigger than 20 characters., For example :, If the content of the file is, Stay positive and happy, Work hard and dont give up hope, Be open to criticism and keep learning, Surround yourself with happy, warm and genuine people, Ans. def BIGLINES():, , p.close(), , Br, , Output:, Work hard and dont give up hope, Be open to criticism and keep learning, , Surround yourself with happy, warm and genuine people, , al, , 33. Write a program to count the no of digits in text file “abc.txt”, Ans. with open(‘abc.txt’,”w”) as f:, , G, , oy, , , L=(“sunday123”,”monday456\n”,”tuesday789\n”), , f.writelines(L), c=0, with open(“abc.txt”,”r”) as e:, , for i in e:, , for j in i:, , if j.isdigit():, , c=c+1, , , print(c), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 79
Page 87 :
or, f=open(“C:\\abc.txt”), k=f.read(), c=0, , , , as, ha, n, , for i in k:, , if i.isdigit():, , print(c), , c=c+1, , Output:, 9, , , , f=open(“story.txt”,”r”), , , , r=f.read(), , , , , A,M=0,0, , for x in r:, , if x==”A” or x==”a” :, , , , A=A+1, , , , ot, , , , f.close(), , M=M+1, , print(“A or a: “,A), , Br, , , , #or if x in[‘A’,’a’], , elif x==”M” or x==”m”:, , , , , he, , , , rs, , Pr, ak, , 34. Write a function AMCount() in Python, which should read each character of a text file STORY.TXT, should count, [SP 21], and display the occurance of alphabets A and M (including small cases a and m too)., Example:, If the file content is as follows:, Updated information, As simplified by official websites., The EUCount() function should display the output as:, A or a:4, M or m :2, Ans. def AMCount():, , print(“M or m: “,M), , G, , oy, , al, , 35. Polina Raj has used a text editing software to type some text in an article. After saving the article as MYNOTES., TXT, she realised that she has wrongly typed alphabet K in place of alphabet C everywhere in the article., Write a function definition for PURETEXT() in python that would display the corrected version of the entire, article of the file MYNOTES.TXT with all the alphabets “K” to be displayed as an alphabet “C” on screen ., , Note: Assuming that MYNOTES.TXT does not contain any C alphabet otherwise., , Example:, If Polina has stored the following content in the file MYNOTES.TXT :, I OWN A KUTE LITTLE KAR., I KARE FOR IT AS MY KHILD., The function PURETEXT() should display the following content:, I OWN A CUTE LITTLE CAR., I CARE FOR IT AS MY CHILD., 3 [OD 17], 80, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 88 :
Ans., 1st Method, , 2nd Method, def PURETEXT():, f=open(“C:\\abc.txt”), p=f.read(), for i in p:, if i==’K’:, print(‘C’,end=””), else:, print(i,end=””), f.close(), , as, ha, n, , def PURETEXT():, c=0, with open(“MYNOTES.TXT”,”r”) as e:, for i in e:, for j in i:, if(j==’K’):, print(‘C’,end=””), else:, print(j,end=””), , Pr, ak, , 36. Write a function Show_words() in python to read the content of a text file ‘NOTES.TXT’ and display the entire, content in capital letters. Example, if the file contains:, “This is a test file”, Then the function should display the output as:, THIS IS A TEST FILE, [2][comptt 2020], Ans., 1st Method, , def Show_words():, f=open(“c:\\abc.txt”), k=f.read(), print(k.upper()), f.close(), , rs, , def Show_words():, f=open(‘NOTES.TXT’,’r’), Lines = f.readlines(), for L in Lines:, print(L.upper()), f.close(), , 2nd Method, , ot, , he, , 37. Write a function Show_words() in python to read the content of a text file ‘NOTES.TXT’ and display only such, lines of the file which have exactly 5 words in them. Example, if the file contains:, “This is a sample file., The file contains many sentences. But need only sentences which have only 5 words.”, Then the function should display the output as:, This is a sample file., 2 [comptt 2020], Ans. def Show_words():, , , , al, , Br, , file=open(‘NOTES.TXT’,’r’), Lines = file.readlines(), for L in Lines:, W=L.split(), , if (len(W)==5):, print(L), file.close(), , G, , oy, , 38. A text file named SOLUTION.TXT contains some English sentences. Another text file named TEST.TXT needs to, be created such that it replaces every occurence of 3 consecutive letters ‘h’, ‘i’ and ‘s’ (irrespective of their cases), from each word of the file SOLUTION.TXT, with 3 underscores (‘__’). For example, if the file SOLUTION.TXT, contains the following content:, “This is his history book.”, Then TEST.TXT should contain the following:, “T___ is ___ ___tory book.”, Write the definition for function CreateTest() in Python that would perform the above task of creating TEST.TXT, from the already existing file SOLUTION.TXT., [3][comptt 2020], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 81
Page 89 :
Ans. def CreateTest():, , as, ha, n, , , file1=open(‘SOLUTION.TXT’,’r’), , file2=open(‘TEST.TXT’,’w’), , lines = file1.readlines(), , for line in lines:, , line=line.replace(“his”,”___”), , file2.write(line), file1.close(), file2.close(), , Pr, ak, , 39. A text file named AGENCIES.TXT contains some text. Write the definition for a function Showsites() in Python, which displays all such words of the file which have more than 9 characters and start with “www.”, for example:, if the file AGENCIES.TXT contains:, [3][comptt 2020], “Name: TechnoCraft, Website: www.technocraft.com,, Name: DataTech, Website: www.datatech.com”, Then the function Showsites() should display the output as:, www.technocraft.com, www.datatech.com, Ans. def Showsites():, , , , file.close(), , he, , rs, , file=open(‘AGENCIES.TXT’,’r’), , lines = file.readlines(), , for line in lines:, , words = line.split(), , for w in words:, if len(w)>9 and w[:4:]== ‘www.’ :, print (w), , 40. Write a method in python to write multiple line of text contents into a text file myfile.txt line., writel():, Ans. def, , Br, , ot, , f=open(‘myfile.txt’,”w”), while True:, line=input(“enter line”), f.write(line), choice=input(“Are there more lines”), if choice ==”N”:, break, f.close(), , al, , , , , , , , , , , 2 [D 16], , oy, , 41. Write a program to take data from user and store in myfile.txt. create another file yourfile.txt and copy, the data from myfile.txt in yourfile.txt. Show the contents of yourfile.txt., Ans. def, writel():, , , , G, , , , , , 82, , f=open(‘myfile.txt’,”w”), while True:, , line=input(“enter line :”), f.write(line), f.write(“\n”), , choice=input(“Are there more lines :”), Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 90 :
as, ha, n, , rs, , :Hello, more lines y, :How, more lines y, :are you, more lines N, , he, , OUTPUT, enter line, Are there, enter line, Are there, enter line, Are there, Hello, How, , Pr, ak, , , if choice ==”N”:, , break, , f.close(), def copy():, , f1=open(“yourfile.txt”,”w”), , f2=open(“myfile.txt”,”r”), , k=f2.read(), , f1.write(k), , f1.close(), , f2.close(), def show():, , with open(“yourfile.txt”,”r”)as e:, , k=e.read(), , print(k), writel(), copy(), show(), , are you, , ot, , 42. Write a program to convert “YOU” into “we” in “abc.txt”, Ans. f=open(‘abc.txt’,”w”), , G, , oy, , al, , Br, , f.write(“you should always close your files, \nin some \, cases, due to buffering, changes made to \, a file may not show \nuntil you close the file”), f.close(), c=0, str=””, with open(“abc.txt”,”r”)as e:, , for i in e:, k=i.split(), , for j in k:, if j.upper()==”YOU”:, , p=”we”, , else:, , p=j, , str=str+p, , str=str+(“ “), , str=str+(“\n”), Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 83
Page 91 :
Output:, we should always close your files,, in some cases, due to buffering, changes made to a file may not show, until we close the file, , as, ha, n, , f = open(“abc.txt”,’w’), f.write(str), f.close(), with open(“abc.txt”,”r”)as e:, , i=e.read(), , print(i), , 43. Text file named “ABC.txt” exist on a disk. Write a program to display the contents of file but the first letter of, the file and first alphabetic character following a comma(“,”) should be in uppercase., Ans. f=open(‘abc.txt’,”w”), , he, , rs, , Pr, ak, , f.write(“You should always close your files, in some\, cases, due to buffering, changes made to\, a file may not show until you close the file”), f.close(), c=0, str=””, with open(“abc.txt”,”r”)as e:, , for i in e:, , k=i.split(“,”), , str=k[0][0].upper(), , str=str+k[0][1:len(k[0])], , for j in range(1,len(k)):, , str=str+(“, “), , str=str+k[j][1].upper(), str=str+k[j][2:], , ot, , , , OR, , to, , buffering,, , G, , oy, , al, , Br, , f=open(‘abc.txt’,”w”), f.write(“You should always close your files, in some\cases, due, changes made to\ a file may not show until you close the file”), f.close(), c=0, str=””, with open(“abc.txt”,”r”)as e:, , for i in e:, , k=i.split(“,”), , l=k[0], , m=k[1:], , str=l[0].upper(), , str=str+l[1:], , for j in m:, , str=str+(“, “), , str=str+j[1].upper(), , str=str+j[2:], print(str), 84, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 92 :
44. Write a statement in Python to open a text file MARKER.TXT so that existing content can be read from it., 1[2019], Ans. file= open(“MARKER.TXT”,”r”), file= open(“MARKER.TXT”,”r+”), , as, ha, n, , OR, , 45. Write a statement in Python to open a text file DATA.TXT so that new contents can be written in it., Ans. file= open(“DATA.TXT”,”w”), , OR, , file= open(“DATA.TXT”,”w+”), , 46. Write a statement in Python to open a text file WRITEUP.TXT so that new content can be written in it. 1[2019], Ans. file= open(“WRITEUP.TXT”,”w”), , OR, , , file= open(“WRITEUP.TXT”,”w+”), , Pr, ak, , 47. Write a statement in Python to open a text file README.TXT so that existing content can be read from it., [2019] 1, Ans. file= open(“README.TXT”,”r”), , OR, , file= open(“README.TXT”,”r+”), , rs, , 48. Write a statement in Python to open a text file CONTENT.TXT so that new contents can be written in it., 1 [comptt 19], Ans. file= open(“CONTENT.TXT”,”c”), , OR, , file= open(“CONTENT.TXT”,”c+”), , ot, , he, , 49. Write a statement in Python to open a text file REMARKS.TXT so that existing content can be read from it., 1 [comptt 19], Ans. file= open(“REMARKS.TXT”,”r”), , OR, , file= open(“REMARKS.TXT”,”r+”), , Seek(), , Br, , The seek method is used to move the file pointer to a specified position., seek has two parameters., , Syntax: f.seek(offset, whence), where f is file pointer, , al, , Parameters:, , Offset: Number of bytes to move (+ or -), whence: This is optional and defaults to 0. It tells where to start from, , oy, , Returns: Does not return any value, The first says how many the second parameter. The former is called offset and the latter is called whence., A positive offset will move the pointer forward, a negative offset would move backward., , G, , The whence can be any of the following values:, os.SEEK_SET or 0 - sets the reference point at the beginning of the file (by default), • os.SEEK_CUR or 1 - sets the reference point at the current file position, •, •, , os.SEEK_END or 2 - sets the reference point at the end of the file, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 85
Page 93 :
50. A text file “abc.txt” containing the following data:, “A switch is called an intelligent hub as it forwards the data packets only to the intended nodes.”, Give the output of the following code, , Output:, s called an intelligent hub as it forwards the data packets only to the intended nodes., tch is called an intelligent hub as it forwards the data packets only to the intended nodes., In the above example when seek(5) is executed, it starts reading from the beginning not from the current position, because by default seek() starts reading from the 0 position., , Pr, ak, , Ans., , , , , as, ha, n, , f=open(“C:\\abc.txt”,”r”), f.seek(10), k=f.read(), # starts reading from the 10th, character, print(k), f.seek(5), # starts reading from the 5th character, k=f.read(), print(k), , Tell(), Tell() method returns current position of file object. This method takes no parameters and returns an integer value, 51. Give the output of the following code, f=open(“C:\\abc.txt”,”r”), , t=f.tell(), , print(“current position=”,t), , rs, , f.seek(10), , k=f.read()# starts reading from the 10th, , he, , print(k), , character, , f.seek(5), , t=f.tell(), , print(“current position=”,t), print(k), , OUTPUT, current position= 10, s called an intelligent hub as it forwards the data packets only to the intended nodes., current position= 5, tch is called an intelligent hub as it forwards the data packets only to the intended nodes., , Br, , Ans., , , , , , # starts reading from the 5th character, , ot, , k=f.read(), , al, , 52. With reference the abc.txt file given above, give the output of the following, f=open(“c:\\abc.txt”), , oy, , k=f.seek(10), g=f.read(5), t=f.tell(), , G, , print(g), print(t), , Ans. OUTPUT, s cal, 15, 86, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 94 :
53. Give the output, f=open(‘C:\\abc.txt’,’r’), f.seek(10), f.seek(5), , as, ha, n, , k=f.tell(), print(k), , Ans. 5, , Absolute Path, , An absolute path is a path that contains the entire path to the file or directory that you need to access. Absolute paths, ensure that Python can find the exact file on your computer. Absolute file paths start with a leading forward slash and, describe how to access a given file or directory, starting from the root of the file system., Relative Path, , Pr, ak, , Generally ’.’ represents the absolute path of the folder where the py file is currently located(parent folder), and ’..’ represents, the absolute path of the upper level folder(parent of parent), of the parent folder where the py file is currently located, If you don’t add a dot, it means the same layer as the py file, that is, the default., , C:\, , The term “parent” directory/folder is used to describe the preceding folder in which a, subfolder or file is created. A parent folder can have many subfolders or files; thus, many, subfolders can share the same parent folder., , rs, , Lets take an example , a folder Test is created in C:\ . Two subfolders Test1 ,Test2 and one, “x.txt” is created in Test Folder. “y.txt” and “Try.py” are created in folder Test1 and “z.txt”, is created in Test2., , he, , 54. Write single line statement in “Try.py” to open the “y.txt” file which is stored in same, parent folder Test1 using absolute path, y.txt, Ans. f=open(“c:\\test\\test1\y.txt”), , Test, x.txt, Test 1, , Test 2, , try.py, , z.txt, , Br, , ot, , 55. Write single line statement in “Try.py” to open the “y.txt” file which is stored in same parent folder Test1 using, relative path, Ans. f=open(“y.txt”), f=open(“.\y.txt”), , or, or, , f=open(“..\\test1\y.txt”), , al, , 56. Write single line statement in “Try.py” to open the “z.txt” file which is stored in folder Test2 using absolute path, Ans. f=open(“c:\\test\\test2\z.txt”), , oy, , 57. Write single line statement in “Try.py” to open the “z.txt” file which is stored in folder Test2 using relative path, Ans. f=open(“..\\test2\z.txt”), , G, , 58. Write single line statement in “Try.py” to open the “x.txt” file which is stored in folder Test using absolute path, Ans. f=open(“c:\\test\\x.txt”), 59. Write single line statement in “Try.py” to open the “x.txt” file which is stored in folder Test using relative path, Ans. f=open(“..\\x.txt”), Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 87
Page 95 :
60. Your teacher has given you a method/function FilterWords() in python which read lines from a text file NewsLetter., TXT, and display those words, which are lesser than 4 characters. Your teachers intentionally kept few blanks in, between the code and asked you to fill the blanks so that the code will run to find desired result. Do the needful, , [CBSE QB], , def FilterWords():, , c=0, , file=open(‘NewsLetter.TXT’, ‘_____’) , , line = file._____, , word = _____, , for c in word:, , if _____: , , print(c), , _________, , FilterWords(), , as, ha, n, , with the following python code., , #Statement-1, #Statement-2, #Statement-3, #Statement-4, #Statement-5, , (d) r, , (ii) Fill in the blank in statement-2 to read the data from the file., (a) File.Read(), (b) read(), (c) read.lines( ), Ans. (b) read(), , (d) readlines( ), , (iii) Fill in the blank in statement-3 to read data word by word., (a) Line.Split(), (b) Line.split(), (c) line.split(), Ans. (c) line.split(), , (d) split.word(), , rs, , Pr, ak, , (i) Write mode of opening the file in statement-1?, (a) a, (b) ab, (c) w, Ans. (d) r, , he, , (iv) Fill in the blank in statement-4, which display the word having lesser than 4 characters., (a) len(c) ==4, (b) len(c)<4, (c) len ( )= =3, (d) len ( )==3, Ans. (b) len(c)<4, (d) end(), , ot, , (v) Fill in the blank in Statement-5 to close the file., (a) file.close(), (b) File.Close(), (c) Close(), Ans. (a) file.close(), , Br, , 61. Which command is used to move the file pointer at 5 position in text file., (i) f.goto(5), (ii) f.postion(5), (iii) f.seek(5), (iv) f.pointer(5), Ans. (iii) f.seek(5), , oy, , al, , 62. Pooja wants to write a function Show_words() in python to read the content of a text file ‘NOTES.TXT’ and, display the entire content in capital letters. She has written some lines of program but facing some problems in, some statements. Help Pooja and fill the missing statement to complete the program., Example, if the file contains:, “This is a test file”, Then the function should display the output as:, THIS IS A TEST FILE, , She has written coding:, , G, , def Show_words():, f=open(‘NOTES.TXT’,’__’), Lines = f.__________, for L in ______:, , print(______), f.close(), 88, , #statement, #statement, #statement, #statement, #statement, , 1, 2, 3, 4, 5, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 96 :
(d) r, , (ii) Fill in the blank in statement-2 to read the data from the file., (a) File.Read(), (b) read(), (c) read.lines( ), Ans. (d) readlines(), , (d) readlines( ), , (iii) Fill in the blank in statement-3 to read data by for loop., (a) Line, (b) data, (c) f, Ans. (a) Line, , (d) NOTES.TXT, , as, ha, n, , (i) Write mode of opening the file in statement-1?, (a) a, (b) ab, (c) w, Ans. (d) r, , (iv) Fill in the blank in statement-4, which display the data in upper case, (a) L.ucase(), (b) upper(L), (c) L.upper(), (d) L.toupper(), Ans. (c) L.upper(), , Binary Files, , 63. Differentiate between Binary Files and Text Files., , Pr, ak, , A binary file is a file stored in binary format. A binary file is computer-readable but not human-readable. All executable, programs are stored in binary files, as are most numeric data files. In contrast, text files are stored in a form (usually, ASCII) that is human-readable, Ans. • Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line),, which is the new line character (‘\n’) in python by default. A text file stores data in the form of alphabets,, digits and other special symbols by storing their ASCII values and are in a human readable format, , he, , rs, , • Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it, into machine understandable binary language. A binary file stores the data in the same way as stored in the, memory. The .exe files, mp3 file, image files, word documents are some of the examples of binary files. We, can’t read a binary file using a text editor., Pickle, , Br, , import pickle, , ot, , Python Pickle is used to serialize and deserialize a python object structure. It’s the process of converting a Python object, into a byte stream to store it in a file/database Any object on python can be pickled so that it can be saved on disk., To use pickle, start by importing it in Python., Writing in file, , for writing in binary file, open the file in ‘wb’(or ‘w+b’) mode., The ‘w’ means that you’ll be writing to the file, and ‘b’ refers to binary mode., , al, , f=open(filename,wb), , using dump():dump() is used for writing in file. It takes two parameter ,the object you want to pickle and the file to, which the object has to be saved., , oy, , dump(‘object to write’, ‘file object’), , Reading from file, , G, , for reading a binary file, open the file in ‘rb’ mode, ‘r’ means you’ll be reading from file., f=open(filename,rb), , using load():load() is used for reading from file. It takes one ‘file object’ parameter, reading data from and then assigned, the contents of file to new variable., Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 89
Page 97 :
Writing list in file, 64. Write a program to create a list L and store it to binary file “test”, Ans. import pickle as p, , , , as, ha, n, , L=[‘a’,’b’,’c’,’d’], with open(‘test’,’wb’) as f:, p.dump(L,f), , Reading file : Unpickle a list, , 65. Write a program to read the data from Binary File “test” and display on screen, Ans. import pickle as p, , output:, [‘a’, ‘b’, ‘c’, ‘d’], , Pickle(Writing) a simple dictionary, 66. Write a program to create pickle file “test” where, (i) write data to pickle file using Dictionary., (ii) read the file and display the contents, Ans. (i) import pickle as p, , , , with open(‘test’,’wb’) as f:, , rs, , , , Dic={1:’Aman’,2:’Karan’,3:’Diya’}, p.dump(Dic,f), , #Unpickle a dictionary, , he, , , , Pr, ak, , with open(‘test’,’rb’) as f:, , L=p.load(f), print(L), , Ans. (ii) with open(‘test’,’rb’) as f:, , , , , , L=p.load(f), , print(L), , ot, , , , output:, {1: ‘Aman’, 2: ‘Karan’, 3: ‘Diya’}, , oy, , al, , Br, , 67. Write a program to add records in pickle file ‘student’ with the following fields, rollno, name of students, marks of subject 1, marks of subject 2, marks of subject 3, sum of marks of all subjcts, Ans. import pickle as p, L=[], , ch=’Y’, , G, , while ch==’Y’ :, , , roll=int(input(“enter rollno”)), , , , sub1=int(input(“enter marks of subject1:”)), , , 90, , name=input(“enter name”), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 98 :
sub2=int(input(“enter marks of subject2:”)), , , , total=sub1+sub2+sub3, , , , , , sub3=int(input(“enter marks of subject3:”)), record=[roll,name,sub1,sub2,sub3,total], L.append(record), , ch=input(“do u want, , as, ha, n, , , , to add more records”).upper(), , , with open(‘student’,’wb’) as f:, , ot, , he, , Output, enter rollno 1, enter name a, enter marks of subject1:33, enter marks of subject2:44, enter marks of subject3:55, do u want to add more records y, enter rollno 2, enter name b, enter marks of subject1:55, enter marks of subject2:66, enter marks of subject3:77, do u want to add more records y, enter rollno 3, enter name c, enter marks of subject1:34, enter marks of subject2:56, enter marks of subject3:78, do u want to add more records n, , Pr, ak, , p.dump(L,f), , rs, , , , L=[], , Br, , 68. Write program to read the above created ‘student’ file and show the contents of file in the following format, roll name total, Ans. import pickle as p, with open(‘student’,’rb’) as f:, L=p.load(f), , al, , , , print(“roll\tName\tTotal”), for r in L:, , print(r[0],r[1],r[5],sep=”\t”), , oy, , , , G, , Output;, roll, Name, 1, a, 2, b, 3, c, Note: r[0] represents to the 1st value, , Total, 132, 198, 168, i.e. rollno, r[1] to the 2nd value and so on., , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 91
Page 99 :
Searching in file, , he, , rs, , Output, enter rollno to serarch 1, name= a, Total= 132, ====================================, enter rollno to serarch 2, name= b, Total= 198, =====================================, enter rollno to serarch 4, not found, , Pr, ak, , L=[], roll=int(input(“enter rollno to serarch”)), with open(‘student’,’rb’) as f:, , L=p.load(f), for r in L:, , if r[0]==roll:, , print(“name=”,r[1]), , print(“Total=”,r[5]), , break, else:, , print(“not found”), , as, ha, n, , 69. Write a program to search for the details (name,total) of student which roll no is read during the execution of, the program., Ans. import pickle as p, , Modify records:, , ot, , 70. Write a program to update the file with a new value of Name. The values of name and rollno are read during, the execution of the program., Ans. import pickle as p, , G, , oy, , al, , Br, , L=[], temp=False, newlist=[], roll=int(input(‘enter rollno to modfiy the name’)), with open(‘student’,’rb’) as f:, , L=p.load(f), for r in L:, , if r[0]==roll:, , temp=True, , print(“name is”,r[1]), , r[1]=input(“enter new name :”), , newlist.append(r), if temp==False:, , print(‘record not found’), else:, , with open(‘student’,”wb”) as f:, , 92, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 100 :
Deleting records:, , as, ha, n, , Output, enter rollno to modfiy the name5, record not found, ====================================, enter rollno to modfiy the name2, name is b, enter new name :z, ====================================, roll, Name, Total, 1, a, 132, 2, z, 198, 3, c, 168, , #or print(r[0],r[1],r[5],sep=”\t”), , Pr, ak, , , p.dump(newlist,f), #print data after modification, with open(‘student’,’rb’) as f2:, , L=p.load(f2), print(‘roll\tName\tTotal’), for r in L:, , print(r[0],’\t’,r[1],’\t’,r[5]), , rs, , 71. Write a program to delete record from pickle file “student”. The value of rollno is taken from user., Ans. import pickle as p, , oy, , al, , Br, , ot, , he, , L=[], temp=False, newlist=[], roll=int(input(‘enter rollno to delete’)), with open(‘student’,’rb’) as f:, , L=p.load(f), for r in L:, , if r[0]==roll:, , temp=True, , print(“roll=”,r[0],”name=”,r[1]), , print(“record deleted”), , else:, , newlist.append(r), if temp==False:, , print(‘record not found’), else:, , with open(‘student’,”wb”) as f:, , p.dump(newlist,f), , G, , =====================================, enter rollno to delete 6, record not found, =====================================, enter rollno to deletion3, roll= 3 name= c, record deleted, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 93
Page 101 :
PROJECT, , as, ha, n, , 72. Write a menu driven program to add, delete, display, modify records in pickle files “emp” using dictionary and, functions. Fields of employee file are :, empno : Empolyee number, name : Name of Employee, salary : Salary of Employee, Bonus : 10% of salary, Ans. import pickle as p, def add():, , , empno=int(input(‘enter empno :’)), , , , sal=int(input(‘enter salary :’)), , , , , , , name=input(‘enter name :’), bonus=sal*10/100, , record={“Empno”:empno,”Name”:name,”Salary”:sal,”Bonus”:bonus}, , Pr, ak, , , , with open(‘d:\project\python\emp’,’ab’) as f:, p.dump(record,f), , def show():, , , f=open(‘d:\project\python\emp’,’rb’), , , , while True:, try:, , , , , print(L[“Empno”],”\t”,L[“Name”],”\t”,L[“Salary”],”\t”,L[“Bonus”]), , , , , L=p.load(f), , rs, , , , print(“Empno\tName\tSalary\tBonus”), , except EOFError:, , he, , , , break, , , , f.close(), , , , f=open(‘d:\project\python\emp’,’rb’), , , , while True:, , , , , , , flag=False, try:, , Br, , , , ot, , def search(empno):, , L=p.load(f), , if L[“Empno”]==empno:, , print(“Empno=”,L[“Empno”]), print(“Name=”,L[“Name”]), , al, , , , , print(“Salary=”,L[“Salary”]), , oy, , , , , , , G, , , , , , print(“Bonus=”,L[“Bonus”]), flag=True, , except EOFError:, , f.close(), , break, , if flag==False:, , print(“record not found”), , def modify(empno):, 94, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 102 :
rec=[], , , , flag=False, , , , try:, , , , , if L[“Empno”]==empno:, , , , print(“Empno\tName\tSalary\tBonus”), , , , , , , , , , , , , , print(L[“Empno”],”\t”,L[“Name”],”\t”, L[“Salary”],”\t”,L[“Bonus”]), L[“Name”]=input(“enter new name”), , , , L[“Salary”]=int(input(“ener new salary”)), L[“Bonus”]=L[“Salary”]*10/100, , , , flag=True, , rec.append(L), , except EOFError:, , f.close(), , break, , if flag==False:, else:, , print(“record not found”), , Pr, ak, , , , L=p.load(f), , as, ha, n, , while True:, , , , f=open(‘d:\project\python\emp’,’wb’), for i in rec:, , , , p.dump(i,f), , , , f.close(), , (2nd method of, , modify), , rs, , , , he, , , , f=open(‘d:\project\python\emp’,’rb’), , ‘‘‘def modify(empno):, , , f=open(‘e:\emp’,’r+b’), , , , t=0;, , , , , , , ot, , , , rec=[], , flag=False, , while True:, , Br, , , , try:, , L=p.load(f), , if L[‘Empno’]==empno:, , al, , , , , , , print(‘Empno\tName\tSalary\tBonus’), , print(L[‘Empno’],’\t’,L[‘Name’],’\t’, L[‘Salary’],’\t’,L[‘Bonus’]), L[‘Name’]=input(‘enter new name’), , L[‘Salary’]=int(input(‘ener new salary’)), , oy, , , , , L[‘Bonus’]=L[‘Salary’]*10/100, , , , G, , , , , , , , flag=True, f.seek(t), , p.dump(L,f), else:, , break, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 95
Page 103 :
t=f.tell(), , except EOFError:, , , , , break, , f.close(), , , , if flag==False:, , , , print(‘record not found’)’’’, , def delete(empno):, , , f=open(‘d:\project\python\emp’,’rb’), , , , flag=False, , , , rec=[], , while True:, , , , try:, , , , , L=p.load(f), , if L[“Empno”]==empno:, , , , Pr, ak, , , , as, ha, n, , , , print(“Empno\tName\tSalary\tBonus”), , , , print(L[“Empno”],”\t”,L[“Name”],”\t”, L[“Salary”],”\t”,L[“Bonus”]), print(“record deleted”), , , , flag=True, , , , else:, , , , except EOFError:, , , , , , break, , f.close(), , if flag==False:, , , , , else:, , , , f=open(‘d:\project\python\emp’,’wb’), for i in rec:, , ot, , , , print(“record not found”), , he, , , , rec.append(L), , rs, , , , , , p.dump(i,f), , , , f.close(), , Br, , ch=”Y”, , while ch==’Y’:, , , , print(“2.show all records”), , print(“3.search any record”), , al, , , , print(“1.add new record”), , , , , print(“5.delete record”), , choice=int(input(“enter your choice :”)), , oy, , , , print(“4.modify record”), , , , , if choice==1:, add(), , elif choice==2:, , , , elif choice==3:, , G, , , , , 96, , show(), , empno=int(input(‘enter empno to search :’)), Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 104 :
empno=int(input(‘enter empno to modfiy :’)), modify(empno), , elif choice==5:, , emn=int(input(‘enter empno to delete :’)), delete(emn), , ch=input(“do u want to continue Y/N :”).upper(), , G, , oy, , al, , Br, , ot, , he, , OUTPUT, 1. add new record, 2. show all records, 3. search any record, 4. modify record, 5. delete record, enter your choice :1, enter empno :101, enter name :aman, enter salary :20000, do u want to continue Y/N :y, 1. add new record, 2. show all records, 3. search any record, 4. modify record, 5. delete record, enter your choice :1, enter empno :102, enter name :rajan, enter salary :25000, do u want to continue Y/N :y, 1. add new record, 2. show all records, 3. search any record, 4. modify record, 5. delete record, enter your choice :1, enter empno :103, enter name :pahul, enter salary :50000, do u want to continue Y/N :y, 1. add new record, 2. show all records, 3. search any record, 4. modify record, 5. delete record, , as, ha, n, , , , elif choice==4:, , Pr, ak, , , , search(empno), , rs, , , , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 97
Page 105 :
as, ha, n, , Bonus, 2000.0, 2500.0, 5000.0, , rs, , Pr, ak, , Salary , 20000 , 25000 , 50000 , , he, , enter your choice :2, Empno, Name , aman, 101, 102, rajan , pahul , 103, do u want to continue Y/N :y, 1. add new record, 2. show all records, 3. search any record, 4. modify record, 5. delete record, enter your choice :3, enter empno to search :102, Empno= 102, Name= rajan, Salary= 25000, Bonus= 2500.0, do u want to continue Y/N :y, 1. add new record, 2. show all records, 3. search any record, 4. modify record, 5. delete record, enter your choice :4, enter empno to modfiy :102, Empno Name, 102 rajan, enter new namekaran, ener new salary15000, do u want to continue Y/N :y, 1. add new record, 2. show all records, 3. search any record, 4. modify record, 5. delete record, enter your choice :2, Empno, Name , 101, aman, karan , 102, 103, pahul , do u want to continue Y/N :y, 1. add new record, 2. show all records, 3. search any record, , Bonus, 2500.0, , Salary , 20000, 15000 , 50000 , , Bonus, 2000.0, 1500.0, 5000.0, , G, , oy, , al, , Br, , ot, , Salary, 25000 , , 98, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 106 :
Bonus, 1500.0, , Pr, ak, , Salary , 15000 , , as, ha, n, , 4. modify record, 5. delete record, enter your choice :5, enter empno to delete :102, Empno, Name , karan, 102, record deleted, do u want to continue Y/N :y, 1. add new record, 2. show all records, 3. search any record, 4. modify record, 5. delete record, enter your choice :6, do u want to continue Y/N :n, , 73. “wb” mode in file handling also can be written as, (i) w*b, (ii) w/b, (iii) w+b, , (iv) none of these, , 74. _________ function is used to write in pickle file., (i) write, (ii) dump, (iii) store, , (iv) pick, , 75. Mode used for reading from pickle file is, (i) rb, (ii) r, , (iv) read, , rs, , (iii) br, , 76. ________ function is used to read from pickle file in python., (i) read, (ii) readdata, (iii) pickread, , (iv) load, , he, , 77. When file is opened as “with open” then file is __________ automatically., (i) read, (ii) write, (iii) close, (iv) open, Ans. 73. (iii), 74. (ii), 75. (i), 76. (iv), 77. (iii), , al, , Br, , ot, , 78. Write a function in Python to search and display details of all those students using display(L) function, whose, stream is “HUMANITIES” from pickled file “Student.dat”. Assuming the pickled file is containing the following, fields :, RNO,Name,Stream,Per, def display(L):, print(L[“RNO”],L[“Name”],L[“Stream”],L[“Per”]), def retstream(L):, return L[“Stream”], Ans. import pickle as p, , def search():, , f=open(‘student.dat’,’rb’), , , , while True:, , oy, , , , , G, , , , , , , , flag=False, try:, , L=p.load(f), , if retstream(L)==”HUMANTIES”, display(L), flag=True, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 99
Page 107 :
f.close(), , break, , if flag==False:, , print(“record not found”), , as, ha, n, , , , except EOFError:, , 79. write a method store_data(record) in python to write the content in a pickled file member.dat., Ans. def store_data(record):, , piFile = open(‘member.dat’,’wb’), , , pickle.dump(record, piFile), piFile.close(), , 80. Considering the following definition of functions, write a method inPython to search and display the content in, a pickled file FACTORY.DAT,where FCTID is matching with the value ‘105’., def Display(s):, , print (s[“FCTID”],s[”FCTNM”],s.[“PROD”]), , Ans. import pickle, , file.close(), , he, , , , rs, , def search( ):, file=open(‘FACTORY.DAT’,’rb’), try:, while True:, f=pickle.load(file), if f[“FCTID”]==105:, Display(f), except EOFError:, pass, , Pr, ak, , , , ot, , 81. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function countrec(), in Python that would read contents of the file “STUDENT.DAT” and display the details of those students whose, percentage is above 75. Also display number of students scoring above 75%, [SP 21], Ans. import pickle, , oy, , al, , Br, , def CountRec():, , fobj=open(“STUDENT.DAT”,”rb”), , num = 0, , try:, , while True:, , rec=pickle.load(fobj), , if rec[2] > 75:, , print(rec[0],rec[1],rec[2],sep=”\t”), , num = num + 1, , except:, , fobj.close(), , return num, , G, , 82. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]., (i) Write a user defined function CreateFile() to input data for a record and add to Book.dat ., (ii) Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and, return number of books by the given Author are stored in the binary file “Book.dat” , [SP 21], , 100, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 108 :
Ans. import pickle, , def createFile():, , , fobj=open(“Book.dat”,”ab”), , , , Book_name=input(“Name :”), , , , , , , , BookNo=int(input(“Book Number : “)), Author = input(“Author: “), , Price = int(input(“Price : “)), , rec=[BookNo,Book_Name,Author,Price], pickle.dump(rec,fobj), fobj.close(), , def CountRec(Author):, , , , fobj=open(“Book.dat”,”rb”), num = 0, try:, , , , , while True:, , Pr, ak, , , , as, ha, n, , , , rec=pickle.load(fobj), , , , if Author==rec[2]:, , , , , except:, , , , num = num + 1, , fobj.close(), , return num, , , , rs, , 83. Consider the following functions declaration and answer the question that follows:, def inputdata(s):, , , , s[“Name”]=input(“enter name”), , s[“marks”]=int(input(“enter marks”)), , def returnmarks(s):, , , he, , , , return s[“marks”], , ot, , def displaydata(s):, , , print (“Name:”,s[“name”]), , , , print (“Percent:”,s[“percent”]), , Br, , Anuj has been asked to display all the students who have scored less than 40 for Remedial classes., Write a user defined function to display all those students who have scored less than 40 from the binary file, “Student.dat” assuming it stores all the object of the class student mentioned above., Ans. import pickle, , al, , def displaydata():, , , X=open(“student.dat”,”rb”), , oy, , , , , , , , G, , , , , , , , break, , try:, , while(X):, , S=pickle.load(X), , if returnmarks(S)<40:, displaydata(S), , , , except EOFError:, , X.close(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 101
Page 109 :
84. Considering the following functions definition, write a method in Python to search and display the content in a, pickled file COMPANY.DAT, where CompID is matching with the value ‘1005’., def Display(self):, , , , print (s[“CompID”],s[“CName”],s[“Turnover”]), , as, ha, n, , Ans. import pickle, , def ques4c( ):, , , file=open(‘COMPANY.DAT’,’rb’), , try:, , while True:, , f=pickle.load(file), , if f[“CompID”]==1005:, , , except EOFError:, , , , file.close(), , , , break, , Pr, ak, , Display(f), , 85. Consider the following definition of function Display(s), write a method in python to search and display the, content in a pickled file emp.dat, where Empno is matching with ‘A0005’. , def Display(s): , , , , print(s[“Empno”],s[“EName”]), , , , f = open(“emp.dat”, ‘rb’) , , , , try: , , he, , , while True: , , rs, , Ans. def search(): , , e = pickle.load(f) , , if e[“Empno”] == ‘A0005’: , , Display(e) , , except EOFError: , , , , f.close(), , pass , , Br, , , , ot, , , , 86. Considering the following definition of functions write a method in python to search and display all the content, in a pickled file CINEMA.DAT, where MTYPE is matching with the value ‘Comedy’., def Show(s):, , print (s[“MNO”],s[“MNAME”],s[“MTYPE”), , al, , , , Ans. def Search():, , file=open(‘CINEMA.DAT’,’rb’), try:, , oy, , , , while True:, , M=pickle.load(file), , G, , if M[“MTYPE”]==”Comedy”:, Show(M), , , , 102, , except EOFError:, pass, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 110 :
def Show(s): , print(s[“Staffcode”],s[“Name’}), Ans. def search(): , f = open(“staff.dat”, ‘rb’) , try: , while True: , e = pickle.load(f) , if e[“Staffcode”] == ‘S0105’: , Show(e) , except EOFError: , pass , f.close(), , and display the content, , as, ha, n, , 87. Consider the following definition function show(), write a method in python to search, in a pickled file staff.dat, where Staffcode is matching with ‘S0105’., , Pr, ak, , 88. Write a definition for function Billing() in Python to read each record of a pickled file STOCK.DAT, and display, the Total Price of all the records in the file. Assume that the file STOCK.DAT is containing following fields, SName and Price, Ans. import pickle, , rs, , def Billing():, , file=open(‘STOCK.DAT’,’rb’), , IRec=pickle.load(file) #To read the object from file, , Totprice=0, , for I in IRec:, , Totprice+=I[1], , print (Totprice), , file.close(), , ot, , he, , 89. A pickled file ELECTION.DAT contains records stored the following fields :, Name,Count, Write the definition for function LowCount() in Python, which reads every record from ELECTION.DAT and, displays every such Name whose Count is less than 10., Ans. import pickle, , Br, , def LowCount():, , file=open(‘ELECTION.DAT’,’rb’), , ERec=pickle.load(file) #To read the object from file, , for E in ERec:, , if E[1] <10:, , print (E[0] ), , file.close(), , al, , 90. Write a method/function MERIT() in python to search and display all the content from a pickled file STUDENT., DAT, where Marks of STUDENT is more than 75.File containing Name and Marks fields., Ans. def MERIT():, , G, , oy, , file=open(‘STUDENT.DAT’,’rb’), , try:, while True:, S=pickle.load(file), if S.Marks > 75:, S.Display(), , except EOFError:, pass, , file.close(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 103
Page 111 :
def COSTLY():, , S=STOCK(), , file=open(‘STOCK.DAT’,’rb’), , try:, , while True:, , S=pickle.load(file), , if S.Price > 1000:, , S.Show(), , except EOFError:, , pass, , , file.close(), , as, ha, n, , Write a method/function COSTLY() in python to search and display Name and Price from a pickled file, STOCK.DAT, where Price of the items are more than 1000., Fields : Name,Price, def Show():, print (Name,”@”,Price), , Pr, ak, , 91., , , , , Ans., , 92. Write a method/function SPLDOCS() in python to search and display all the content from a pickled file DOCS., DAT, where Specialisation of DOCTORS is “CARDIOLOGY”., def Disp():, print (Name,”#”,Specialisation), Ans. def SPLDOCS():, , , D=DOCTORS(), , , , try:, , , , file=open(‘DOCS.DAT’,’rb’), while True:, , D=pickle.load(file), , he, , , , if D.Specialisation == ‘CARDIOLOGY’:, , , , , except EOFError:, , , , file.close(), , D.Disp(), , ot, , , , , rs, , , , pass, , oy, , al, , Br, , 93. Amritya Seth is a programmer, who has recently been given a task to write a python code to perform the following, binary file operations with the help of two user defined functions/modules:, [CBSE QB], (a) AddStudents() to create a binary file called STUDENT.DAT containing student information – roll number,, name and marks (out of 100) of each student., (b) GetStudents() to display the name and percentage of those students who have a percentage greater than 75., In case there is no student having percentage > 75 the function displays an appropriate message. The function, should also display the average percent.He has succeeded in writing partial code and has missed out certain, statements, so he has left certain queries in comment lines., You as an expert of Python have to provide the missing statements and other related queries based on the following, code of Amritya., Answer any four questions (out of five) from the below mentioned questions., , G, , import pickle, def AddStudents():, , ____________, #1 statement to open the binary file to write data, , while True:, , Rno = int(input(“Rno :”)), 104, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 112 :
Name = input(“Name : “), , , , L = [Rno, Name, Percent], , Percent = float(input(“Percent :”)), , , , ____________, , , , Choice = input(“enter more (y/n): “), , , , , #2 statement to write the list L into the file, , if Choice in “nN”:, break, , , , F.close(), , , , Total=0, , , , Countabove75=0, , def GetStudents():, , , , , Countrec=0, , with open(“STUDENT.DAT”,”rb”) as F:, while True:, , , , try:, , , , Pr, ak, , , , ____________ #3 statement to read from the file, Countrec+=1, , Total+=R[2], , , , if R[2] > 75:, , , , print(R[1], “ has percent = “,R[2]), , , , except:, , , , if Countabove75==0:, , print(“There is no student who has percentage more than 75”), , average=Total/Countrec, , print(“average percent of class = “,average), , AddStudents(), GetStudents(), , ot, , , , break, , he, , , , , Countabove75+=1, , rs, , , , , , as, ha, n, , , , al, , Br, , (i) Which of the following commands is used to open the file “STUDENT.DAT” for writing only in binary, format? (marked as #1 in the Python code), (a) F= open(“STUDENT.DAT”,’wb’), (b) F= open(“STUDENT.DAT”,’w’), (c) F= open(“STUDENT.DAT”,’wb+’), (d) F= open(“STUDENT.DAT”,’w+’), Ans. (a) F= open(“STUDENT.DAT”,’wb’), , G, , oy, , (ii) Which of the following commands is used to write the list L into the binary file, STUDENT.DAT? (marked, as #2 in the Python code), (a) pickle.write(L,f) , (b) pickle.write(f, L), (c) pickle.dump(L,F) , (d) f=pickle.dump(L), Ans. (c) pickle.dump(L,F), , (iii) Which of the following commands is used to read each record from the binary file STUDENT.DAT?, (marked as #3 in the Python code), (a) R = pickle.load(F) , (b) pickle.read(r,f), (c) r= pickle.read(f) , (d) pickle.load(r,f), Ans. (a) R = pickle.load(F), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 105
Page 113 :
as, ha, n, , (iv) Which of the following statement(s) are correct regarding the file access modes?, (a) ‘r+’ opens a file for both reading and writing. File object points to its beginning., (b) ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it exists and, creates a new one if it does not exist., (c) ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and creates, a new one if it does not exist., (d) ‘a’ opens a file for appending. The file pointer is at the start of the file if the file exists., Ans. (a), (v) Which of the following statements correctly explain the function of seek() method?, (a) tells the current position within the file., (b) determines if you can move the file position or not., (c) indicates that the next read or write occurs from that position in a file., (d) moves the current file position to a given specified position, Ans. (d), , rs, , #Statement-1, #Statement-2, , ot, , he, , def search(r):, f = open(“student.dat”,____), ____:, , while True:, , rec = pickle.____, , if(____):, , print(rec), except:, , pass, ____ , , Pr, ak, , 94. Arun, during Practical Examination of Computer Science, has been assigned an incomplete search() function, to search in a pickled file student.dat. The File student.dat is created by his Teacher and the following, information is known about the file., • File contains details of students in [roll_no,name,marks] format., • File contains details of 10 students (i.e. from roll_no 1 to 10) and separate list of each student is written in, the binary file using dump()., Arun has been assigned the task to complete the code and print details of roll number1., [CBSE QB], , #Statement-3, #Statement-4, , #Statement-5, , G, , oy, , al, , Br, , (i) In which mode Arun should open the file in Statement-1?, (a) r, (b) r+, (c) rb, (d) wb, Ans. (c) rb, (ii) Identify the suitable code to be used at blank space in line marked as Statement2, (a) if(rec[0]==1), (b) for i in range(10) (c) try, (d) pass, Ans. (c) try, (iii) Identify the function (with argument), to be used at blank space in line marked as Statement-3., (a) load(), (b) load(student.dat), (c) load(f), (d) load(fin), Ans. (c) load(f), (iv) What will be the suitable code for blank space in line marked as Statement-4., (a) rec[0]=r, (b) rec[1]==r, (c) rec[2]=r, (d) rec[0]==r, Ans. (d) rec[0]==r, (v) Which statement Arun should use at blank space in line marked as Statement4 to close the file., (a) file.close(), (b) close(file), (c) f.close(), (d) close(), Ans. (c) f.close(), , 106, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 114 :
Function, , Explanation, To open a file, , close(), , Close an open file, , read(n), , Reads ‘n’ characters from the file till end of the file, , readline(), , Read and return one line from the file, , readlines(), , Reads and returns all the lines from the file, , seek(offset), , Change the cursor position by bytes as specified by the offset, , tell(), , Returns the current file location, , write(), , Writes a string of data to the file, , writelines(), , Writes a list of data to the file, , Pr, ak, , as, ha, n, , open(), , CSV FILES, , 95. What is a CSV File?, Ans. A CSV (Comma Separated Values) file is a type of plain text file that uses specific structuring to arrange tabular, data. A CSV file is a simple text file where each line contains a list of values (or fields) delimited by commas., , , , G, , oy, , al, , Br, , ot, , he, , rs, , 96. How to create csv file?, Ans. CSV file can be created in excel, notepad, wordpad etc., (a) In Excel : Open the new excel file, store some data then click on save as and save it as .csv extension, , (b) In notepad: Open new file in notepad write some data delimited by commas, To save the file select save as option and then give any name to file with .csv extension., , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 107
Page 115 :
as, ha, n, , Pr, ak, , , , rs, , Reading a CSV File, using reader() : The reader() function takes a file object and returns a _csv.reader object that can be used to iterate, over the contents of a CSV file., 97. Write a program to read a test.csv file (saved in d:\), Ans. import csv, data=csv.reader(f), for row in data:, , , print(row), , ot, , f.close(), , he, , f=open(“d:/test.csv”,”r”), , , , Br, , import csv, , , , print(row), , or, , with open(‘d:/test.csv’, ‘r’) as f:, for row in data:, , al, , , , data = csv.reader(f), , G, , oy, , Output:, [‘roll’, ‘name’, ‘marks’], [‘1’, ‘aleeka’, ‘4’], [‘2’, ‘aleeza’, ‘85’], [‘3’, ‘alina’, ‘95’], [‘4’, ‘ananya’, ‘14’], [‘5’, ‘ananya’, ‘62’], [‘6’, ‘arni’, ‘46’], [‘7’, ‘bhavna’, ‘78’], 108, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 116 :
[‘8’, ‘divya’, ‘100’], [‘9’, ‘harshita’, ‘83’], [‘10’, ‘himanshi’, ‘90’], 98. Write a program to read test.csv and show data in tabular form (without comma), , as, ha, n, , Ans. import csv, f=open(“d:/test.csv”,”r”), csvreader=csv.reader(f), for rows in csvreader:, print(‘\t’.join(rows)), , f.close(), , or, , import csv, f=open(“d:/test.csv”,”r”), csvreader=csv.reader(f), for rows in csvreader:, , , print(rows[0],rows[1],rows[2]), , f.close(), , name, , , , 1, , aleeka, , , , 2, , aleeza, , , , 3, , alina, , , , 4, , , , 5, , , , 6, , , , 7, , , , 8, , , , 9, , next(), , 85, 95, 14, , ananya, , 62, , arni, , 46, , bhavna, , 78, , divya, , 100, , harshita, , 83, , himanshi, , 90, , ot, , 10, , 4, , ananya, , Br, , , , marks, , rs, , roll, , he, , , , Pr, ak, , , , al, , The next() method returns the current row and moves to the next row., 99. Write a program to count the no of records in “test.csv” file, , oy, , Ans. import csv, , f=open(“d:/test.csv”,”r”), data=csv.reader(f), , G, , L=list(data), row_count=len(L)-1, , #Excludes header row, , print(“Total rows :”,row_count), f.close(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 109
Page 117 :
or, Alternately, you can use next(f) to skip header row, import csv, , next(f), , #skips the first row, , data=csv.reader(f), L=list(data), , row_count=len(L), , print(“Total rows :”,row_count), f.close(), , or, , import csv, , with open(“d:/test.csv”,”r”) as f:, next(f), , , , print(“Total rows :”,len(list(data))), , , , #skips the first row, , data=csv.reader(f), , or, , import csv, , count=0, , with open(“d:/test.csv”,”r”) as f:, next(f), , , , data=csv.reader(f), , , , count=count+1, , he, , , , for row in data:, , rs, , , , , , print(“Total rows :”,count), , count=0, , ot, , import csv, , , , next(f), , , , Br, , with open(“d:/test.csv”,”r”) as f:, , , , Pr, ak, , , , as, ha, n, , f=open(“d:/test.csv”,”r”), , data=csv.reader(f), , or, , #skips the first row, , count=sum(1 for row in data), , print(“Total rows:”,count), , OUTPUT, , al, , , Total rows : 10, , oy, , 100. Write a program to read test.csv file and show the sum of all marks, Ans. import csv, sum=0, , with open(“d:/test.csv”,”r”) as f:, next(f), , , , for row in csvreader:, , G, , , , , , csvreader=csv.reader(f), sum+=int(row[2]), , print(“sum of marks :”,sum), 110, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 118 :
L=[], with open(“d:/test.csv”,”r”) as f:, , next(f), , csvreader=csv.reader(f), , for row in csvreader:, , L.append(int(row[2])), print(“Sum of marks :”,sum(L)), print(“Maximum marks:”, max(L)), print(“Minimum marks:”, min(L)), , or, , OUTPUT:, Sum of marks : 657, Maximum marks: 100, Minimum marks: 4, , rs, , , , , , , Pr, ak, , import csv, with open(“d:/test.csv”,”r”) as f:, , next(f), , csvreader=csv.reader(f), , L=[int(row[2]) for row in csvreader], print(“Sum of marks :”,sum(L)), print(“Maximum marks:”, max(L)), print(“Minimum marks:”, min(L)), , as, ha, n, , 101. Write a program to show sum, minimum and maximum values of marks in csv file “test.csv”, Ans. import csv, , Searching in file, , he, , 102. Write a program to search the record from “test.csv” file on the basis of input rollno. If record not found display, message “record not found”, Ans. import csv, , oy, , al, , Br, , ot, , f=open(“d:/test.csv”,”r”), csvreader=csv.reader(f), next(f), r=int(input(“enter roll no to search”)), for rows in csvreader:, , if int(rows[0])==r:, , print(“name =”,rows[1]), , print(“marks=”,rows[2]), , break, else:, , print(“record not found”), f.close(), , G, , Output:, enter roll no to search 5, name = ananya, marks = 62, ====================================, enter roll no to search 15, record not found, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 111
Page 119 :
Writing to CSV File, csv.writer(): The csv.writer() function is used to create a writer object. The writer.writerow() function is then used to, write single row to the CSV file., using writerow(): writerow takes 1-dimensional data (one row) to write., (a) Write a program to write records onto a csv file ‘stud.csv’ and display all records., Ans. import csv, , with open(“stud.csv”, “w”) as f:, , , field=[“RollNo”,”Name”], , , , csv_writer.writeheader(), , , , as, ha, n, , 103., , csv_writer=csv.DictWriter(f,fieldnames=field,lineterminator=’\n’), , with open(“stud.csv”, “a”) as f1:, , , csv_writer=csv.writer(f1,lineterminator=’\n’), , , , while ch==’Y’:, , ch=’Y’, , , , Pr, ak, , , , r=int(input(‘enter roll :’)), , , , n=input(‘enter name :’), , , , rec=[r,n], , , , csv_writer.writerow(rec), , ch=input(‘more records(Y/N)?’).upper(), , , , print(‘Records are’), , with open(‘stud.csv’, ‘r’) as csvfile:, csvreader = csv.reader(csvfile), for rows in csvreader:, , , , , OUTPUT, , Br, , ot, , enter roll :1, enter name :aa, more records(Y/N)?y, enter roll :2, enter name :bb, more records(Y/N)?n, Records are, [‘RollNo’, ‘Name’], [‘1’, ‘aa’], [‘2’, ‘bb’], In excel file;, , G, , oy, , al, , , , , , , , , , , , , , print(rows), , he, , , , rs, , , , using writerows() : if you need to write the contents of the 2-dimensional list to a CSV file, then you can, use writerows ()., 112, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 120 :
(b) Write a program to write records in one single go onto a csv file ‘stud.csv’ and display all records., Ans. import csv, , with open(“stud.csv”, “w”) as f:, , , field=[“RollNo”,”Name”], , , , csv_writer.writeheader(), , csv_writer=csv.DictWriter(f,fieldnames=field,lineterminator=’\n’), , ch=’Y’, L=[], , while ch==’Y’:, , , r=int(input(‘enter roll :’)), , , , rec=[r,n], , , , n=input(‘enter name :’), , , , L.append(rec), , ch=input(‘more records(Y/N)?’).upper(), , with open(“stud.csv”, “a”) as f1:, , , Pr, ak, , , , as, ha, n, , , , csv_writer=csv.writer(f1,lineterminator=’\n’), , , , csv_writer.writerows(L), , print(‘Records are’), , with open(‘stud.csv’, ‘r’) as csvfile:, csvreader = csv.reader(csvfile), , , , for rows in csvreader:, , ot, , OUTPUT, enter roll :1, enter name :jj, more records(Y/N)?y, enter roll :2, enter name :kk, more records(Y/N)?n, Records are, [‘RollNo’, ‘Name’], [‘1’, ‘jj’], [‘2’, ‘kk’], , Br, , , , , , , , , , , , , , print(rows), , he, , , , rs, , , , al, , 104. What is the difference between Writerow () and Writerows () in CSV file?, Ans. So writerow takes 1-dimensional data (one row), and writerows takes 2-dimensional data (multiple rows). So the, only difference is that writerows lets you pass multiple values., , oy, , CSV Files with Delimiters, Delimiter specifies the character used to separate each field. The default is the comma ( ‘,’ )., However, CSV files can use delimiters other than a comma. Few popular ones are | and \t., , G, , Line Terminatoer, A line terminator is a string used to terminate lines produced by writer objects. The default value is \r\n ., , Example:, import csv, , f1=open(‘stud.csv’, ‘w’), Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 113
Page 124 :
G, , oy, , al, , Br, , ot, , he, , rs, , Pr, ak, , as, ha, n, , , L=[], , field=[], , data = csv.reader(f), , field=next(data), , for rows in data:, , if int(rows[0])==e:, , print(“salary”,rows[1]), , print(“dept name=”,rows[2]), , s=int(input(“enter salary”)), , n=input(“enter new name”), , L.append([e,s,n]), , print(“record modified”), , flag=1, , else:, , L.append(rows), , if flag==0:, , print(“record not found”), , else:, , f=open(“emp.csv”,”w”), , csv_writer=csv.DictWriter(f,fieldnames=field,lineterminator=’\n’), , csv_writer.writeheader(), , csv_writer=csv.writer(f,lineterminator=”\n”), , csv_writer.writerows(L), , f.close()’’’, import os, ch=’Y’, addheader(), while ch==’Y’:, , print(‘1.add record’), , print(‘2.Show all records’), , print(‘3.Show recods of particular department’), , print(‘4.Count no of records’), , print(“5.Delete Records”), , print(“6.Modify records”), , choice=int(input(‘enter your choice’)), , if choice==1:, , add(), , elif choice==2:, , show(), , elif choice==3:, , dt=input(‘enter dept name’), , showdept(dt), , elif choice==4:, , count(), , elif choice==5:, , e=int(input(“enter empno to delete”)), , delete(e), Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 117
Page 125 :
elif choice==6:, , , , modify(e), , , , , e=int(input(“enter empno to Modify”)), , ch=input(‘continue(Y/N)?’).upper(), , , , , with open(“stud.csv”, “r”) as csvfile:, csvreader = csv.reader(csvfile), , , , for rows in csvreader:, , , , if rows[2]>=75:, , , , print(rows), , as, ha, n, , 107. Write a function display () in python to display all the students who have got a distinction (scored percentage, more than or equal to 75) from a csv file “stud.csv”, assuming the csv file is containing the following fields:, roll,name,percentage, Ans. def display():, , , , , Pr, ak, , 108. Write a function in python to read the objects trom csv file named WORKER.CSV and display those records, of workers, whose Wage is less than 300, assuming the csv file is containing the following fields:, workerid,name,wages, Ans. def display():, with open(“worker.csv”, “r”) as csvfile:, csvreader = csv.reader(csvfile), , , , for rows in csvreader:, if rows[2]<3000:, , rs, , , , print(“workder id=”,rows[0]), , , , print(“name=”,rows[1]), , he, , , , , , , , with open(“drink.csv”, “a”, newline=’’) as csv:, , Br, , , , ot, , 109. Write functions in python to perform the following:, (i) Write the records onto csv file “drink.csv”., (ii) Read the contents from csv file and display them on the screen when DNAME has value “INDY COLA”., The csv file is containing the following fields:, Dcode,Dname,Dprice, Ans. (i) def add():, csv_writer=csv.writer(csv), , c=int(input(“enter Dcode :”)), , p=int(input(“enter Dprice :”)), d=input(“enter Dname :”), , al, , , , , oy, , , , rec=[c,p,d], , csv_writer.writerow(rec), , (ii) def display():, , , , G, , , , , , 118, , with open(“drink.csv”, “r”) as csvfile:, csvreader = csv.reader(csvfile), for rows in csvreader:, , if rows[1]==”INDY COLA”:, print(rows), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 126 :
with open(“customer.csv”, ‘w’, newline=’’)as csv:, csv_writer=csv.writer(csv), c=int(input(“enter custno :”)), n=input(“enter name :”), rec=[c,n], csv_writer.writerow(rec), , as, ha, n, , 110. Write a function in python to assign a new object in a csv file “customer.csv”. Assume the csv file is containing, following fields., custno, Name, Ans. def add():, , Pr, ak, , 111. Write definition of a function CALSAL( ) in python to find the total salary paid to all the workers in a company., The worker’s detail of this company is stored in a csv file WORKERS.csv., Assume that the file workers.csv is containing the following fields, WID(int), Name(string), Salary(float), Ans. def CALSAL():, sum=0, with open(“workers.csv”,”r”) as f:, # to skip header, next(f), csvreader=csv.reader(f), for row in csvreader:, , sum+=float(row[2]), , he, , , , rs, , , , , , , , print(“sum of salary :”,sum), , with open(“USER.csv”, “r”) as csvfile:, csvreader = csv.reader(csvfile), for rows in csvreader:, if rows[2]==”A”:, print(rows), , al, , , , , , , , Br, , ot, , 112. Write a function in python to read and display the detail of all the users whose status is “A” (i.e. Active) from, a csv file “USER.csv”. Assuming the csv file “USER.CSV” is containing following fields:, int Uid; // User Id, Stirng Uname // User Name, String Status; // User Type: A Active I Inactive, Ans. def display():, , G, , oy, , 113. Given a csv file GAME.CSV, containing records of the following structure type, GameName ,Participant, Write a function in python that would read contents from the file GAME.CSV and creates a file named BASKET., CSV copying only those records from GAME.CSVwhere the game name is “Basket Ball”, Ans. def copyrec():, , , , with open(‘GAME.CSV’, ‘r’) as csvfile:, csvreader = csv.reader(csvfile), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 119
Page 128 :
1. AKSHAY,XII,A , 3. ARVIND,XII,A , 5. ASHISH,XII,A, Incomplete Code, , 2. ABHISHEK,XII,A, 4. RAVI,XII,A, , import_____, , #Statement-1, , fh = open(_____, _____, newline=’’), , #Statement-2, , stuwriter = csv._____, , #Statement-3, , data = [], , for i in range(5):, , Pr, ak, , header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’], data.append(header), , as, ha, n, , 115. No. 1 Rohit, a student of class 12th, is learning CSV File Module in Python. During examination, he has been, assigned an incomplete python code (shown below) to create a CSV File ‘Student.csv’ (content shown below)., Help him in completing the code which creates the desired CSV File., [CBSE QB], CSV File, , roll_no = int(input(“Enter Roll Number : “)), name = input(“Enter Name : “), , Class = input(“Enter Class : “), , section = input(“Enter Section : “), data.append(rec), , stuwriter. _____ (data, fh.close(), , rs, , rec = [_____], , #Statement-4, #Statement-5, , he, , (i) Identify the suitable code for blank space in line marked as Statement-1., (a) csv file, (b) CSV, (c) csv, Ans. (c) csv, , (d) Csv, , ot, , (ii) Identify the missing code for blank space in line marked as Statement-2?, (a) “School.csv”,”w” , (b) “Student.csv”,”w”, (c) “Student.csv”,”r” , (d) “School.csv”,”r”, Ans. (b) “Student.csv”,”w”, , Br, , (iii) Choose the function name (with argument) that should be used in the blank space of line marked as, Statement-3, (a) reader(fh), (b) reader(MyFile), (c) writer(fh), (d) writer(MyFile), Ans. (c) writer(fh), , G, , oy, , al, , (iv) Identify the suitable code for blank space in line marked as Statement-4., (a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’ , CLASS, SECTION, (c) ‘roll_no’,’name’,’Class’,’section’ , co.connect(), Ans. (d) roll_no,name,Class,section, , (b) R O L L _ N O , N A M E ,, (d) roll_no,name,Class,sectionc), , (v) Choose the function name that should be used in the blank space of line marked as Statement-5 to create, the desired CSV File?, (a) dump(), (b) load(), (c) writerows(), (d) writerow(), Ans. (c) writerows(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 121
Page 129 :
as, ha, n, , 116. Radha Shah is a programmer, who has recently been given a task to write a python code to perform the following, CSV file operations with the help of two user defined functions/modules:, (a) CSVOpen() : to create a CSV file called BOOKS.CSV in append mode containing information of books –, Title, Author and Price., (b) CSVRead() : to display the records from the CSV file called BOOKS.CSV where the field title starts with, ‘R’., , She has succeeded in writing partial code and has missed out certain statements, so she has left certain queries, in comment lines., , import csv, , #Statement-1, #Statement-2, #Statement-3, , Pr, ak, , def CSVOpen():, with open(‘books.csv’,’______’,newline=’’) as csvf:, cw=______, ______, cw.writerow([‘Rapunzel’,’Jack’,300]), cw.writerow([‘Barbie’,’Doll’,900]), cw.writerow([‘Johnny’,’Jane’,280]), def CSVRead():, try:, with open(‘books.csv’,’r’) as csvf:, cr=______, for r in cr:, if ______:, print(r), except:, print(‘File Not Found’), CSVOpen(), CSVRead(), , #Statement-4, , rs, , #Statement-5, , he, , , , , , , , , , , , , , , , , , , , , G, , oy, , al, , Br, , ot, , You as an expert of Python have to provide the missing statements and other related queries based on the following, code of Radha., Answer any four questions (out of five) from the below mentioned questions., (i) Choose the appropriate mode in which the file is to be opened in append mode (Statement 1), (a) w+, (b) ab, (c) r+, (d) a, Ans. (d) a, (ii) Which statement will be used to create a csv writer object in Statement 2., (a) csv.writer(csvf), (b) csv.writer(csvf), (c) csvf.writer(), (d) cs.writer(csvf), Ans. (b) csv.writer(csvf), (iii) Choose the correct option for Statement 3 to write the names of the column headings in the CSV file,, BOOKS.CSV., (a) cw.writerow(‘Title’,’Author’,’Price’), (b) cw.writerow([‘Title’,’Author’,’Price’]), (c) cw.writerows(‘Title’,’Author’,’Price’), (d) cw.writerows([‘Title’,’Author’,’Price’]), Ans. (b) cw.writerow([‘Title’,’Author’,’Price’]), (iv) Which statement will be used to read a csv file in Statement 4., (a) cs.read(csvf), (b) csv.reader(csvf), (c) csvf.read(), (d) csvf.reader(cs), Ans. (b) csv.reader(csvf), (v) Fill in the appropriate statement to check the field Title starting with ‘R’ for Statement 5 in the above, program., (a) r[0][0]==’R’, (b) r[1][0]==’R’, (c) r[0][1]==’R’d., (d) r[1][1]==’R’, Ans. (a) r[0][0]==’R’, 122, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 130 :
SECTION : B, , CBSE SAMPLE QUESTION PAPER, Maximum Marks : 35, , as, ha, n, , (Released by CBSE for the academic year 2021-22), , Time Allowed : 90 Minutes, , General Instructions :, 1. The question paper is divided into 3 Sections - A, B, and C., 2. Section A consists of 25 Questions (1-25). Attempt any 20 questions., 3. Section B consists of 24 Questions (26-49). Attempt any 20 questions., 4. Section C consists of 6 case study based Questions (50-55). Attempt any 5 questions., 5. All questions carry equal marks., , Pr, ak, , SECTION - A, , G, , oy, , al, , Br, , ot, , he, , rs, , This section consists of 25 Questions (1 to 25). Attempt any 20 questions from this section. Choose the best, possible option., 1. Find the invalid identifier from the following:, (a) none, (b) address, (c) Name, (d) pass, 2. Consider the declaration L = 1, ‘Python’, ‘3.14’. What will be the data type of L?, (a) list, (b) tuple, (c) dictionary, (d) string, 3. Given an object obj1= (10, 20, 30, 40, 50, 60, 70, 80, 90). What will be the output of print(obj1[3:7:2])?, (a) (40,50,60,70,80), (b) (40,50,60,70), (c) (40,50,60), (d) (40,60), 4. Which of the following statements is not correct?, (a) If we try to read a text file that does not exist, an error occurs., (b) If we try to read a text file that does not exist, the file gets created., (c) If we try to write on a text file that does not exist, no error occurs., (d) If we try to write on a text file that does not exist, the file gets created., 5. Which of the following options can be used to read the first line of a text file “Myfile.txt”?, (a) myfile = open(‘Myfile.txt’); print(myfile.read(line)), (b) myfile = open(‘Myfile.txt’,’r’); print(myfile read(1)), (c) myfile = open(‘Myfile.txt’); print(myfile.readline()), (d) myfile = open(‘Myfile.txt’); print(myfile.readlines()), 6. Assume that the position of the file pointer is at the beginning of 3rd line in a text file. Which of the following, options can be used to read all the remaining lines?, (a) myfile.read(n-3), (b) myfile.read(n), (c) myfile.readline(), (d) myfile.readlines(), 7. A text file “student.txt” is stored in the storage device. Identify the correct option out of the following, options to open the file in read mode., (i) myfile = open(‘student.txt’,’a’), (ii) myfile = open(‘student.txt’,’w’), (iii) myfile = open(‘student.txt’,’r’), (iv) myfile = open(‘student.txt’), (a) only (i), (b) both (i) and (iv), (c) both (iii) and (iv), (d) both (i) and (iii), 8. The return type of the input() function is, (a) string, (b) integer, (c) list, (d) tuple, 9. Which of the following operator cannot be used with string data type?, (a) +, (b) in, (c) *, (d) /, 10. Given an object obj1 = (10, 15, 25, 30). Identify the statement that will result in an error., (a) print(obj1[2]), (b) obj1[2] = 20, (c) print(min(obj1)), (d) print(len(obj1)), Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 123
Page 131 :
he, , rs, , Pr, ak, , as, ha, n, , 11. Which of the following statements is incorrect in the context of binary files?, (a) Information is stored in the same format in which the information is held in memory., (b) No end of line (EOL) character translation takes place., (c) Every line ends with a new line character., (d) pickle module is used for reading and writing., 12. What is the significance of the tell() method?, (a) tells the path of the file., (b) tells the current position of the file pointer within the file., (c) tells the end position within the file., (d) checks the existence of a file at the desired location., 13. Which of the following statements is true?, (a) pickling creates an object from a sequence of bytes., (b) pickling is used for object serialization., (c) pickling is used for object deserialization., (d) pickling is used to manage all types of files in Python., 14. Syntax of seek function in Python is myfile.seek(offset, reference_point) where myfile is the file object. What is, the default value of reference_point?, (a) 0, (b) 1, (c) 2, (d) 3, 15. Which of the following components are part of a function header in Python?, (i) function name , (ii) return statement, (iii) parameter list , (iv) def keyword, (a) only (i), (b) (i) and (iii), (c) (iii) and (iv), (d) (i), (iii) and (iv), 16. Which of the following function headers is correct?, (a) def cal_si(p=100, r, t=2): , (b) def cal_si(p=100, r=8, t):, (c) def cal_si(p, r=8, t): , (d) def cal_si(p, r=8, t=2):, 17. Which of the following is the correct way to call a function?, (a) my_func(), (b) def my_func(), (c) return my_func, (d) call my_func(), 18. Which of the following characters act as default delimiter in a CSV file?, (a) (colon) :, (b) (hyphen) (c) (comma),, (d) (vertical line) |, 19. Given below is one way of opening a file Student.csv file in write mode., , ot, , myfile = open(“Student.csv”,”w”,newline=’’)., , Br, , What is the importance of newline=’’?, (a) A new line gets added to the file., (c) Empty string gets appended to all lines., 20. Consider the following python program., , (b) Empty string gets appended to the first line., (d) EOL character translation is suppressed., , al, , import csv, fh = open(“Student.csv”,”r”), stureader = csv.reader(fh), for rec in stureader:, print(rec), , G, , oy, , What will be the data type of rec?, (a) string, (b) list, (c) tuple, 21. Which of the following is not a function/method of the csv module in Python?, (a) read(), (b) reader(), (c) writer(), 22. Which one of the following is the default extension of a Python file?, (a) .exe, (b) .p++, (c) .py, 23. Which of the following symbol is used in Python for comments?, (a) $, (b) @, (c) //, , 124, , (d) dictionary, (d) writerow(), (d) .p, (d) #, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 132 :
Pr, ak, , 25. Which of the following statements is false in the context of dictionary?, (a) The values of a dictionary can be accessed using keys., (b) The keys of a dictionary can be accessed using values., (c) Elements in a dictionary are in form of key:value pairs., (d) Dictionaries are mutable., , as, ha, n, , 24. Which of the following statements opens a binary file “record.bin” in write mode and writes an object lst1, = [1,2,3,4] on the binary file?, (a) with open(‘record.bin’,’wb’) as myfile:, pickle.dump(lst1,myfile), (b) with open(‘record.bin’,’wb’) as myfile:, pickle.dump(myfile,lst1), (c) with open(‘record.bin’,’wb+’) as myfile:, pickle.dump(myfile,lst1), (d) with open(‘record.bin’,’ab’) as myfile:, pickle.dump(myfile,lst1), , SECTION - B, , This section consists of 24 Questions (26 to 49). Attempt any 20 questions., 26. What is the output of the following code?, , T=(100), , print(T*2), , (b) (200,), , (c) 200, , rs, , (a) Syntax error, , (d) (100,100), , 27. Suppose the content of Myfile.txt is:, , he, , Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, , ot, , What will be the output of the following code?, , (a) 3, , Br, , myfile = open(“Myfile.txt”), data = myfile.readlines(), print(len(data)), myfile.close(), , (b) 4, , (c) 106, , (d) 22, , oy, , al, , 28. Identify the output of the following Python statements., x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]], y = x[1][2], (a) 11.0, , print(y), , (b) 12.0, , (c) 14.0, , (d) 15.0, , (c) 2345678, , (d) 23456789, , G, , 29. Identify the output of the following Python statements., x = 2, while x < 9:, print(x, end=’’), , (a) 12345678, , x = x + 1, , (b) 3456789, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 125
Page 133 :
30. Identify the output of the following Python statements., , (b) 33, , (c) 36, , 31. Identify the output of the following Python statements., lst1 = [10, 15, 20, 25, 30], lst1.insert( 3, 4), , (a) 2, , lst1.insert( 2, 3), print (lst1[-5]), , (b) 3, , (c) 4, , (d) 39, , as, ha, n, , (a) 31, , b = 1, for a in range(1, 10, 2):, b += a + 2, print(b), , (d) 20, , 32. Raghav is trying to write an object obj1 = (1,2,3,4,5) on a binary file “test.bin”. Consider the following, code written by him., , Pr, ak, , import pickle, obj1 = (1,2,3,4,5), myfile = open(“test.bin”,’wb’), pickle., #Statement 1, myfile.close(), , rs, , Identify the missing code in Statement 1., (a) dump(myfile,obj1), (b) dump(obj1, myfile), (c) write(obj1,myfile), (d) load(myfile,obj1), , he, , 33. The content of a binary file “employee.dat” is shown below where the Header is not a part of file content, (i.e only Row1 to Row5 are present in the file), Empno, , Empname, , Salary, , 101, , Anuj, , 50000, , 102, , Arijita, , 40000, , Row3, , 103, , Hanika, , 30000, , Row4, , 104, , Firoz, , 60000, , Row5, , 105, , Vijaylakshmi, , 40000, , Header, Row1, , Br, , ot, , Row2, , G, , oy, , al, , def display(eno):, f=open(“employee.dat”,”rb”), totSum=0, try:, while True:, R=pickle.load(f), if R[0]==eno:, , 126, , #Line1, , totSum=totSum+R[2], , except:, f.close(), print(totSum), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 134 :
When the above-mentioned function, display (103) is executed, the output displayed is 190000. Which of the, following statement should be used in the blank space of the line marked as Line1 to obtain the above output?, (a) jump, (b) break, (c) continue, (d) return, def add (num1, num2):, sum = num1 + num2, sum = add(20,30), print(sum), , (a) 50, , (b) 0, , (c) Null, , 36. What will be the output of the following code?, , (d) None, , (d) 32, , Pr, ak, , 35. Evaluate the following expression and identify the correct answer., 16 - (4 + 2) * 5 + 2**3 * 4, (a) 54, (b) 46, (c) 18, , as, ha, n, , 34. What will be the output of the following Python code?, , def my_func(var1=100, var2=200):, var1+=10, , var2 = var2 - 10, return var1+var2, , print(my_func(50),my_func()), , (a) 100 200, , (b) 150 300, , (c) 250 75, , (d) 250 300, , value = 50, , he, , def display(N):, , rs, , 37. What will be the output of the following code?, , global value, , value = 25, if N%7==0:, , ot, , value = value + N, , else:, , Br, , value = value - N, , print(value, end=”#”), display(20), , al, , (a) 50#50, , print(value), , (b) 50#5, , (c) 50#30, , (d) 5#50#, , 38. Which of the following options can be the output for the following code?, , oy, , import random, List=[“Delhi”,”Mumbai”,”Chennai”,”Kolkata”], , G, , for y in range(4):, x = random.randint(1,3, print(List[x],end=”#”), , (a) Delhi#Mumbai#Chennai#Kolkata#, (c) Mumbai# Mumbai #Mumbai # Delhi#, , (b) Mumbai#Chennai#Kolkata#Mumbai#, (d) Mumbai# Mumbai #Chennai # Mumbai, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 127
Page 135 :
39. What is the output of the following code snippet?, def ChangeVal(M,N):, , if M[i]%5 == 0: M[i]//=5, if M[i]%3 == 0: M[i]//=3, L = [25,8,75,12], ChangeVal(L,4), for i in L:, , print(i,end=”#”), , (a) 5#8#15#4#, , (b) 5#8#5#4#, , (c) 5#8#15#14#, , 40. Suppose the content of “Myfile.txt” is, , What will be the output of the following code?, , (d) 5#18#15#4#, , Pr, ak, , Humpty Dumpty sat on a wall, Humpty Dumpty had a great fall, All the king’s horses and all the king’s men, Couldn’t put Humpty together again, , as, ha, n, , for i in range(N):, , myfile = open(“Myfile.txt”), , record = myfile.read().split(), print(len(record)), myfile.close(), , (b) 25, , (c) 26, , 41. Find the output of the following code:, , (d) 27, , he, , Name=”PythoN3@1”, , rs, , (a) 24, , ot, , R=””, for x in range(len(Name)):, if Name[x].isupper(): R=R+Name[x]., lower(), , Br, , elif Name[x].islower(): R=R+Name[x]., upper(), elif Name[x].isdigit():, R=R+Name[x-1], , (b) pYTHOnN#@, , al, , (a) pYTHOn##@, , else: R=R+”#”, print(R), , (c) pYTHOn#@, , (d) pYTHOnN@#, , 42. Suppose the content of “Myfile.txt” is, , oy, , Honesty is the best policy., , What will be the output of the following code?, , G, , myfile = open(“Myfile.txt”), , 128, , x = myfile.read(), , (a) 5, , print(len(x)), myfile.close(), , (b) 25, , (c) 26, , (d) 27, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 136 :
What will be the output of the following code?, myfile = open(“Myfile.txt”), x = myfile.read().lower(), y = x.count(‘umpty’), print(y), myfile.close(), , (a) 2, , (b) 3, , (c) 4, , x = 3, def myfunc():, global x, x+=2, print(x, end=’ ‘), print(x, end=’ ‘), myfunc(), print(x, end=’ ‘), , (a) 3 3 3, , (b) 3 5 3, , (c) 3 3 5, , (d) 3 5 5, , rs, , 45. Suppose the content of “Myfile.txt” is, , (d) 5, , Pr, ak, , 44. What will be the output of the following code?, , as, ha, n, , 43. Suppose the content of “Myfile.txt” is, Humpty DUMPTY sat on a wall, Humpty DUMPTY had a great fall, All the king’s horses and all the king’s men, Couldn’t put Humpty together again, , Ek Bharat Shreshtha Bharat, What will be the output of the following code?, , (a) 6, , Br, , ot, , he, , myfile = open(“Myfile.txt”), vlist = list(“aeiouAEIOU”), vc=0, x = myfile.read(), for y in x:, if(y in vlist):, vc+=1, print(vc), myfile.close(), , (b) 7, , (c) 8, , (d) 9, , oy, , al, , 46. Suppose the content of “Myfile.txt” is, Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, Twinkle twinkle little star, , G, , What will be the output of the following code?, , myfile = open(“Myfile.txt”), line_count = 0, data = myfile.readlines(), for line in data:, if line[0] == ‘T’:, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 129
Page 137 :
line_count += 1, print(line_count), myfile.close(), , (c) 4, , (d) 5, , as, ha, n, , (a) 2, (b) 3, 47. Consider the following directory structure., , School, , Examination, , Academics, , Sports, , Result.png, , Syllabus.jpg, , Achievement.jpg, , Pr, ak, , Suppose root directory (School:\) and present working directory are the same. What will be the absolute path, of the file Syllabus.jpg?, (a) School/Syllabus.jpg, (b) School/Academics/Syllabus.jpg, (c) School/Academics/../Syllabus.jpg, (d) School/Examination/Syllabus.jpg, 48. Assume the content of the text file “Myfile.txt” is:, , rs, , Arjun Kumar, Ismail Khan, Joseph B, Hanika Kiran, , What will be the data type of data_rec?, , he, , myfile = open(“Myfile.txt”), data_rec = myfile.readlines(), myfile.close(), , (c) tuple, , (d) dictionary, , (b) (1,2,[1,3.14],3), , (c) (1,2,[1,2],3.14), , (d) Error Message, , (a) string, (b) list, 49. What will be the output of the following code?, , ot, , tup1 = (1,2,[1,2],3), tup1[2][1]=3.14, print(tup1), , Br, , (a) (1,2,[3.14,2],3), , SECTION - C, , Case Study Based Questions., , G, , oy, , al, , This section consists of 6 Questions (50-55). Attempt any 5 questions., Rohit, a student of class 12, is learning csv module in Python. During the examination, he has been given a stub, Python program (shown below) to create a CSV File “Student.csv” (content shown below). Help him in, completing the code which creates the desired CSV File., , 130, , CSV File, 1,AKSHAY,XII,A, 2,ABHISHEK,XII,A, 3,ARVIND,XII,A, 4,RAVI,XII,A, 5,ASHISH,XII,A, Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 138 :
Incomplete Code, , #Statement-1, #Statement-2, #Statement-3, ‘SECTION’], Number : “)), “), : “), , as, ha, n, , import _____, fh = open(_____, _____, newline=’’), stuwriter = csv._____, data = [ ], header = [‘ROLL_NO’, ‘NAME’, ‘CLASS’,, data.append(header), for i in range(5):, , roll_no = int(input(“Enter Roll, , name = input(“Enter Name : “), , Class =, input(“Enter Class :, , section = input(“Enter Section, , rec = [ _____ ], data.append(_____), stuwriter. _____ (data), fh.close(), , #Statement-4, #Statement-5, #Statement-6, , (d) csv module, , 51. Identify the missing code for blank space in the line marked as Statement-2., (a) “Student.csv”,”wb”, (b) “Student.csv”,”w”, (c) “Student.csv”,”r”, , (d) “Student.csv”,”rb”, , Pr, ak, , 50. Identify the suitable code for blank space in the line marked as Statement-1., (a) csv file, (b) CSV, (c) csv, , 52. Choose the function name (with argument) that should be used in the line marked as Statement-3., (a) reader(fh), (b) reader(MyFile), (c) writer(fh), (d) riter(MyFile), , rs, , 53. Identify the suitable code for the blank space in Statement-4., (a) ‘ROLL_NO’, ‘NAME’, ‘CLASS’, ‘SECTION’, (b) ROLL_NO, NAME, CLASS, SECTION, (c) ‘roll_no’, ‘name’, ‘Class’, ‘section’, (d) roll_no, name, Class, section, 54. Identify the suitable code for blank space in Statement-5., (a) data, (b) record, (c) rec, , he, , (d) insert, , 4. (b), 14. (a), , 5. (c), 15. (d), , 6. (d), 16. (d), , 7. (c), 17. (a), , 8. (a), 18. (c), , 9. (d), 19. (d), , 10. (b), 20. (b), , 22. (c), 32. (b), 42. (d), , 23. (d), 33. (c), 43. (b), , 24. (a), 34. (d), 44. (d), , 25. (b), 35. (c), 45. (b), , 26. (c), 36. (d), 46. (a), , 27. (b), 37. (b), 47. (b), , 28. (d), 38. (b), 48. (b), , 29. (c), 39. (b), 49. (b), , 30. (c), 40. (c), 50. (c), , 52. (c), , 53. (d), , 54. (c), , 55. (c), , G, , oy, , 51. (b), , Answers, , 3. (d), 13. (b), , al, , 21. (a), 31. (b), 41. (b), , 2. (b), 12. (b), , Br, , 1. (d), 11. (c), , ot, , 55. Choose the function name that should be used in the blank space of the line marked as Statement-6 to create, the desired CSV File?, (a) dump(), (b) load(), (c) writerows(), (d) writerow(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 131
Page 139 :
SECTION : C, , MODEL TEST PAPER – 1, , Maximum Marks : 35, , as, ha, n, , (Based on the Latest CBSE Sample Paper), Time Allowed : 90 Minutes, , General Instructions :, 1. The question paper is divided into 3 Sections - A, B, and C., 2. Section A consists of 25 Questions (1-25). Attempt any 20 questions., 3. Section B consists of 24 Questions (26-49). Attempt any 20 questions., 4. Section C consists of 6 case study based Questions (50-55). Attempt any 5 questions., 5. All questions carry equal marks., , Pr, ak, , SECTION - A, , This section consists of 25 Questions (1 to 25). Attempt any 20 questions from this section. Choose the best, possible option., 1. Find the invalid identifier from the following:, (a) Total*Tax, (b) While, , (c) Column31, , (d) switch, , (d) string, , 3. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90)., What will be the output of print (t [3::2])?, (a) (40,60,80), (b) (30,50,70), (c) (30,050,70,90), , (d) (40,60), , the following options is correct?, is opened in r mode, file is opened, is opened in r mode, file is opened, is opened in r mode, file is opened, is opened in r mode, file is opened, , ot, , 4. Which of, (a) if file, (b) if file, (c) if file, (d) if file, , he, , rs, , 2. Consider a declaration L = {“1”:(1,2,3)}, Which of the following represents the data type of L?, (a) list, (b) tuple, (c) dictionary, , for, for, for, for, , reading only, reading and writing both, writing only, reading and appending, , Br, , 5. Which of the following options can be used to read complete text file as String?, (a) myfile = open(‘Myfile.txt’); myfile.read(), (b) myfile = open(‘Myfile.txt’,’r’); myfile.read(n), (c) myfile = open(‘Myfile.txt’); myfile.readline(), (d) myfile = open(‘Myfile.txt’); myfile.readlines(), , al, , 6. Assume that the position of the file pointer is at the beginning of 3rd line in a text file. Which of the following, option can be used to read the 3rd line?, (a) myfile.read(), (b) myfile.readline(3), (c) myfile.readline(), (d) myfile.readlines(), , oy, , 7. Identify the correct option out of the following options to open the binary file in write mode., (a) myfile = open(‘student’,’wb’), (b) myfile = open(‘student’,’w+b’), (c) myfile = open(‘student’,’bw’), (d) all of the above, , G, , 8. Choose the correct function name required to check if a string contains only uppercase letters., (a) isupper(), (b) upper(), (c) toupper(), (d) onlyupper(), 9. Which of the following is not valid?, (a) “5”*3, (b) “5” in [“1”,”2”,”5”], , (c) ”5”+”5”, , (d) ”5”/”5”, , 10. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect?, (a) print(T[1]), (b) T.append(5), (c) max(T), (d) len(T), , 132, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 140 :
12. What is the significance of the tell() method?, (a) tell the length of file, (b) tell the current position of the file pointer, (c) tell the type of file, (d) tell the end position within file, , as, ha, n, , 11. Which of the following statements is correct in the context of binary files?, (a) A binary file stores the data in the same way as stored in the memory., (b) We can read a binary file using a text editor., (c) Every line ends with a new line character., (d) A binary file stores data in their ASCII values and are in a human readable format., , 13. Which of the following statements is correct to store list L in binary file object f.p is the object of pickle library?, (a) p.dump(L,f), (b) L.dump(p,f), (c) f.dump(L,p), (d) p.dump(f,L), , 15. Function blocks begin with the _______________ ., (a) fun, (b) define, , (c) 2, , (d) 3, , Pr, ak, , 14. Minimum argument required in seek function is, (a) 0, (b) 1, , 16. Which of the following function header is incorrect?, (a) def sum(a,b,c), (b) def sum(a,b,c=10), , (c) def, , (d) open, , (c) def sum(a,b=5,c=10), , (d) def sum(a=4,b,c=10), , (d) call func(), , 18. Which of the following characters acts as default delimiter in a csv file?, (a) (hash) #, (b) (dot) ., (c) (comma) ,, , (d) (vertical line) |, , 19. Choose the correct option for reading csv file., (a) data=csv.reader(f), (b) data=csv[reader.f], , (d) data=csv(reader.f), , he, , rs, , 17. Which of the following is the correct way to call a function?, (a) func(), (b) def func(), (c) call func, , (c) data=csv.reader[f], , 20. Which method returns the current row and moves to the next row in csv file?, (a) move(), (b) next(), (c) cur(), , (d) currow(), , 22. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90), What will be the output of print(t[-2:])?, (a) (80, 90), (b) (80), (c) no output, , (d) (90, 80), , 23. Choose the correct name of the immutable data object from the following:, (a) List, (b) Set, (c) String, , (d) Dictionary, , 24. The file pointer is placed at the beginning of the file when the file is opened in, (a) r, (b) r+, (c) rb, , (d) all of the above, , oy, , al, , Br, , ot, , 21. Which of the following options is incorrect?, (a) Reading and Writing both can be done when file is opened in r+ mode., (b) When file is opened in r+ mode the file pointer is placed at the beginning of the file., (c) Only Reading in binary file can be done when file is opened in rb+ mode., (d) When file is opened in rb+ mode the file pointer is placed at the beginning of the file., , G, , 25. Which of the following is false about a dictionary?, (a) Keys and values are unique within a dictionary, (b) The values of a dictionary can be of any type., (c) The keys must be of an immutable data type such as strings, numbers, or tuples., (d) Each key-value pair maps the key to its associated value., , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 133
Page 141 :
SECTION - B, This section consists of 24 Questions (26 to 49). Attempt any 20 questions., a=20, b=30, a,b=b+20,a+30, print(a,b), , (a) 50,50, , (b) 50,80, , (c) 70 50, , 27 Suppose content of ‘Myfile.txt’ is:, , What will be the output of the following code?, , f = open(“Myfile.txt”), data=f.readline(), data=f.readline(), print(data), f.close(), , 28. Identify the output, , he, , t=(3,2,1), print(t*3), , (b) How I wonder what you are, (d) Twinkle twinkle little star, How I wonder what you are, , rs, , (a) Twinkle twinkle little star, (c) Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, , (a) (9,6,3), , (d) 70 80, , Pr, ak, , Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, , as, ha, n, , 26. What is the output of following code:, , (b) (3,2,1,3,2,1,3,2,1), , (c) (3,3,3,2,2,2,1,1,1), , (d) (3,2,1),(3,2,1),(3,2,1), , ot, , 29. How many times will the following loop execute and give the output?, , Br, , z=7, sum=0;, while z<=12:, sum=sum+z, z=z+2, print(z), , (a) 3 times, output-13, , (b) 3 times,output-12, , (c) 4 times,output-11, , (d) 4 times,output-12, , al, , 30. What will be displayed after the execution of the following loop?, , oy, , Total,End=5,15;, for Turn in range(1,End,2):, Total+=1, print(Total,Turn), , (a) 11,12, , (b) 13,13, , (c) 11,15, , (d) 12,13, , (b) [1,2,3,5,3], , (c) [1,2,4,5,3], , (d) [1,2,3,4,5], , G, , 31. Select the correct output, , 134, , L=[1,2,3,4,5,3], L.pop(3), print(L), , (a) [1,2,4,5], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 142 :
import pickle as p, Dic={1:’Aman’,2:’Karan’,3:’Diya’}, with open(‘test’,’wb’) as f:, , _________________, , #statement 1, , Identify the missing code in Statement 1., (a) p=dump(f), (b) p.dump(Dic,f), , (c) p,dump(f,Dic), , (d) f.dump(Dic,p), , Salary, 50000, 40000, 30000, 60000, 40000, , Pr, ak, , 33. A binary file employee.dat has following data, Empno, empname, 101, Anuj, 102, Arijita, 103, Hanika, 104, Firoz, 105, Vijaylakshmi, , as, ha, n, , 32. Rahul is trying to write a Dictionary Dic={1:’Aman’,2:’Karan’,3:’Diya’} on a binary file test.bin., Consider the following code written by him., , rs, , def display(eno):, , f=open(“employee.dat”,”rb”), , totSum=0, try:, , while True:, , R=pickle.load(f), , if R[0]==eno:, , __________ #Line1, , totSum=totSum+R[2], , except:, , f.close(), , print(totSum), , , he, , When the above mentioned function, display (103) is executed, the output displayed is 90000., Write appropriate jump statement from the following to obtain the above output., (a) jump, (b) break, (c) continue, (d) return, 34. What will be the output of the following Python code?, , Br, , ot, , def sum(a,b=10):, , print(a+b), , sum(15,25), sum(15), , (a) 40, (b) 25, (c) 35, (d) 40, 25 25 15 10, , al, , 35. Evaluate the following expression and identify the correct answer., x = 6 + 36/6 + 2*5, (a) 45.0, (b) 17.0, (c) 26.25, , (d) 22.0, , oy, , 36. Observe the following code carefully and find which statement will never get executed in the code., , G, , counter=1, while counter<=15:, , if counter<15:, , print(“Jump”), , else:, , print(“Stop”), , counter+=4, , (a) statement2, , (b) statement4, , #statement1, #statement2, #statement3, #statement4, #statement5, #statement6, #statement7, , (c) statement6, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , (d) statement7, 135
Page 143 :
def fun():, , a=10, , print(a,end=”#”), a=5, fun(), print(a), , (a) 10#5, , (b) 10#10, , (c) 5#5, , 38. What are the possible outcome(s) executed from the following code?, , (i) ES#NE#IO#, (a) (i) and (ii), , (ii) LE#NO#ON#, (b) (ii) and (iii), , (d) 5#10, , Pr, ak, , import random, STRING=”CBSEONLINE”, NUMBER=random.randint(0,3), N=9, while STRING[N]!=”L”:, , print (STRING[N], +STRING[NUMBER] + “#”,end=””), , NUMBER=NUMBER+1, , N=N-1, , as, ha, n, , 37. What will be the output of the following code?, , (iii) NS#IE#LO#, (c) (i) and (iv), , (iv) EC#NB#IS#, (d) (iii) and (iv), , 39. What output will be generated when the following Python code is executed?, , Br, , ot, , he, , rs, , def ChangeList():, L=[ ], , L1=[ ], , , L2=[ ], , for i in range(1,10):, , L.append(i), for i in range(10,1,-2):, , L1.append(i), , , for i in range(len(L1)):, L2.append(L1[i]+L[i]), , , L2.append(len(L)-len(L1)), , print (L2), ChangeList(), , (a) [11, 10, 9, 8, 7, 4], , (b) [4,7,8,9,10,11], , (c) [2,4,6,8,10,11], , (d) [10,8,6,4,2,11], , oy, , al, , 40. Suppose content of ‘Myfile.txt’ is, Humpty Dumpty sat on a wall, Humpty Dumpty had a great fall, All the king’s horses and all the king’s men, Couldn’t put Humpty together again, , What will be the output of the following code?, , G, , myfile = open(“Myfile.txt”), record = myfile.readline().split(), print(len(record)), myfile.close(), , (a) 4, , 136, , (b) 5, , (c) 6, , (d) 7, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 144 :
(c) EAR1, , (d) EA11, , Pr, ak, , (a) EARN, (b) EA12, 42. Suppose content of ‘Myfile.txt’ is, , as, ha, n, , 41. Find the output, , def Findoutput():, , L=”earn”, , x=” “, , count=1, , for i in L:, , if i in[‘a’,’e’,’i’,’o’,’u’]:, x=x+i.swapcase(), else:, if count%2!=0:, , x=x+str(len(L[:count])), else:, , count =count +1, print (x), Findoutput(), , Honesty is the best policy., Be Honest., What will be the output of the following code?, , myfile = open(“Myfile.txt”), x = myfile.read(), print(len(x)), myfile.close(), , (d) 38, , he, , rs, , (a) 35, (b) 36, (c) 37, 43. Which of the following options can be used to read the 2nd line of a text file?, (a) file=f.readlines() , (b) file=f.readline(), print(file[1]) print(file[1]), (c) file=f.read() , (d) file=f.readlines(), print(file[1]) print(file[2]), 44. Observe the following program and answer the questions that follow:, , Br, , ot, , import random, X=3, N=random.randint(1,X), for i in range(N):, , print (i,”#”,i+1), , al, , Find out, which of output(s) out of (a) to (d) will not be expected from the program?, (a) 0#1, (b) 1#2, (c) 2#3, (d) 3#4, 45. In f=open(“abc.txt”,”w”), f refers to, (a) file name, (b) file object, (c) file access mode, (d) file pointer, 46. When the method display() is executed it reads lines from a text file DIARY.TXT, and display those lines, which, are starting with an alphabet ‘P’., , G, , oy, , def display():, , file=open(‘DIARY.TXT’,’r’), , l=file.readlines(), , for line in l:, , if _________ :, # statement 1, , print (line), , file.close(), , Select the appropriate statement to fill the statement 1., (a) line[1]= =’P’, (b) line[0] =’P’, (c) line(0)= =’P’, Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , (d) line[0]= =’P’, 137
Page 145 :
f=open(“c:\\abc.txt”), k=f.seek(10), g=f.read(5), t=f.tell(), print(t), , (a) 5, , (b) 6, , (c) 10, , 48. Which method is used to read the entire file in the form of string?, (a) read(), (b) readline(), (c) readlines(), 49. What will be the output of the following code?, , (a) two#6#two, , (b) one#6#one, , (c) two#6#one, , (d) 15, , (d) all of these, , (d) two#5#two, , Pr, ak, , lt2=[[‘one’,’two’,’three’],[4,5,6]], print(lt2[0][1],end=”#”), print(lt2[-1][-1],end=”#”), print(lt2[0][1]), , as, ha, n, , 47. Give the output, , SECTION - C, Case Study Based Questions., , This section consists of 6 Questions (50-55). Attempt any 5 questions., , Fields of CSV File :roll,name, Incomplete Code, , rs, , Pahul, a student of class 12, is learning CSV File Module in Python. During Final Project he was facing some, problems in code. An incomplete python code (shown below) to create a CSV File ‘Stud.csv’. Help him in, completing the code which creates the desired CSV File., , al, , Br, , ot, , he, , import csv, f1=________________, #statement, csv_writer=csv.writer(f1,delimiter=’|’,lineterminator=’,’), ch=’Y’, while ch==’Y’:, r=int(input(‘enter roll :’)), n=input(‘enter name :’), rec=[r,n], __________________, #statement, ch=input(‘more records(Y/N)?’).upper(), print(‘Records are’), _________, #statement, with ________________:, #statement, csvreader = ____________, #statement, ___________________:, #statement, print(rows), , 1, , 2, 3, 4, 5, 6, , oy, , 50. Identify the suitable code for blank space in the line marked as Statement-1., (a) f1=open(‘stud.csv’, ‘w’), (b) f1=open(‘stud.csv’, ‘r’), (c) f1=open(‘stud.csv’, ‘rw’), (d) f1=open(‘stud.csv’), , G, , 51. Identify the suitable code for blank space in the line marked as Statement-2., (a) csv_writer.writerows(rec), (b) csvwriter.writerow(rec), (c) csv.writer.writerow(rec), (d) csv_writer.writerow(rec), 52. Identify the suitable code for blank space in the line marked as Statement-3., (a) close(f1), (b) .f1.close(), (c) close[f1], , 138, , (d) f1(close), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 146 :
53. Identify the suitable code for blank space in the line marked as Statement-4., (a) open(‘stud.csv’, ‘rt’) as csvfile, (b) .open(‘stud.csv’, ‘rb’) as csvfile, (c) open(‘stud.csv’) as csvfile , (d) open(‘stud.csv’, ‘w’) as csvfile, , as, ha, n, , 54. Identify the suitable code for blank space in the line marked as Statement-5., (a) csv.reader(csvfile) , (b) csv_reader(csvfile), (c) csvreader(csvfile) , (d) csv.reader(file), , 55. Identify the suitable code for blank space in the line marked as Statement-6., (a) for rows in csv_reader , (b) for rows in csv.reader, (c) for rows in csvreader , (d) for rows in range [csvreader], , Answers (Model Test Paper – 1), 2. (c), 12. (b), , 3. (a), 13. (a), , 4. (a), 14. (b), , 5. (a), 15. (c), , 6. (c), 16. (d), , 7. (a), 17. (a), , 21. (c), 31. (b), 41. (d), , 22. (a), 32. (b), 42. (d), , 23. (c), 33. (b), 43. (a), , 24. (d), 34. (a), 44. (d), , 25. (a), 35. (d), 45. (b), , 26. (a), 36. (c), 46. (d), , 27. (b), 37. (a), 47. (d), , 51. (d), , 52. (b), , 53. (c), , 54. (a), , 55. (c), , 8. (a), 18. (c), , 9. (d), 19. (a), , 10. (b), 20. (b), , 28. (b), 38. (c), 48. (a), , 29. (a), 39. (a), 49. (a), , 30. (d), 40. (c), 50. (a), , G, , oy, , al, , Br, , ot, , he, , rs, , Pr, ak, , 1. (a), 11. (a), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 139
Page 147 :
MODEL TEST PAPER – 2, , (Based on the Latest CBSE Sample Paper), Time Allowed : 90 Minutes, , as, ha, n, , Maximum Marks : 35, , General Instructions :, 1. The question paper is divided into 3 Sections - A, B, and C., 2. Section A consists of 25 Questions (1-25). Attempt any 20 questions., 3. Section B consists of 24 Questions (26-49). Attempt any 20 questions., 4. Section C consists of 6 case study based Questions (50-55). Attempt any 5 questions., 5. All questions carry equal marks., , SECTION - A, , 1. Find the invalid identifier from the following, (a) 3rdRow, (b) Finally, , Pr, ak, , This section consists of 25 Questions (1 to 25). Attempt any 20 questions from this section. Choose the best, possible option., (d) _Total, , 2. Consider a declaration L = “15”, Which of the following represents the data type of L?, (a) list, (b) tuple, (c) dictionary, , (d) string, , 3. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90)., What will be the output of print (t [::2])?, (a) (10, 30), (b) (80, 90), (c) (10, 30, 50, 70, 90), , (d) [10, 30, 50, 70, 90], , rs, , (c) Column31, , ot, , he, , 4. Which of the following options is correct?, (i) if file is opened in r mode, the file pointer is placed at the beginning of the file, (ii) if file is opened in r mode, the file pointer is placed at the end of the file, (iii) if file is opened in r+ mode, the file pointer is placed at the beginning of the file, (iv) if file is opened in r + mode, the file pointer is placed at the end of the file, (a) only (i), (b) (i) and (iii) both, (c) (ii) and (iii) both, (d) (ii) and (iv), , Br, , 5. Which of the following options can be used to read all the lines and return them as each line is a string element, in a list?, (a) myfile = open(‘Myfile.txt’); myfile.read(), (b) myfile = open(‘Myfile.txt’,’r’); myfile.read(n), (c) myfile = open(‘Myfile.txt’); myfile.readline(), (d) myfile = open(‘Myfile.txt’); myfile.readlines(), , G, , oy, , al, , 6. Assume that the position of the file pointer is at the beginning of 3rd line in a text file. Which of the following, options can be used to read all the remaining lines?, (i) myfile.read(), (ii) myfile.read(n), (iii) myfile.readline(), (iv) myfile.readlines(), (a) (i) and (iii), (b) (i) and (iv), (c) (ii) and (iv), (d) (ii) and (iii), , 140, , 7. Identify the correct option out of the following options to open the text file for reading and writing both., (i) myfile = open(‘student.txt’,’r+’), (ii) myfile = open(‘student.txt’,’w+’), (iii) myfile = open(‘student.txt’,’rw’), (iv) myfile = open(‘student.txt’,r+w+), (a) only (i), (b) both (i) and (iv), (c) both (iii) and (iv), (d) both (i) and (ii), 8. Choose the correct function name required to check the total length of the list., (a) length(), (b) len(), (c) size(), , (d) dimension(), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 148 :
9. Which is not a valid string?, (a) ‘hello’, (b) “hello”, , (c) ‘‘‘hello’’’, , (d) hello, , 10. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect?, (a) sum(T), (b) min(T), (c) max(T), (d) avg(T), , 12. _______________ method tells the current position of file pointer., (a) tell(), (b) pos(), (c) cur(), , as, ha, n, , 11. Which of the following statements is incorrect in the context of binary files?, (a) A binary file stores the data in the same way as stored in the memory., (b) We can read a binary file using a text editor., (c) The .exe files, mp3 file, image files, word documents are some of the examples of binary files., (d) There is no terminator for a line., (d) pointer(), , 13. _______________ module is used for serializing and de-serializing a Python object structure., (a) random, (b) math, (c) serial, (d) pickle, , Pr, ak, , 14. In seek(), value _______________ sets the reference point at the current file position., (a) 0, (b) 1, (c) 2, (d) 3, 15. A function, (a) can’t return any value , (c) can return 1 or 2 value , , (b) can return only 1 value, (d) can return many values, , 16. Which of the following function header is incorrect?, (a) def greater(a,b), (b) def greater(a=5,b), , (c) def greater(a=5,b=10), , (d) def greater(a,b=10), , (d) call func(), , 18. Delimiter specifies the character used to separate _______________, (a) each field, (b) each word, (c) each line, , (d) each character, , 19. Which method can be used to read data from csv file?, (a) readdata(), (b) read(), (c) reader(), , (d) readcsv(), , 20. Which function is used to create a writer object in csv file?, (a) csv.writer(), (b) csv.write(), (c) csv.writedata(), , (d) csv.writerow(), , ot, , he, , rs, , 17. Which of the following is the correct way to call a function?, (a) func(), (b) func, (c) call func, , is correct?, writing only, in w mode that exists, overwrites the file, in w mode that does not exist, the file gets Created., , 22. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90), What will be the output of print(t[:4:])?, (a) (10, 20, 30, 40), (b) (50), (c) (50,60,70,80,90), , (d) (10,20,30,40,50), , 23. Choose the correct name of the mutable data object from the following:, (a) Int, (b) Tuple, (c) String, , (d) Dictionary, , 24. The file pointer is placed at the beginning of the file when the file is opened in, (a) r mode, (b) w mode, (c) a mode, , (d) all of the above, , oy, , al, , Br, , 21. Which of the following options, (a) Opens a file in w mode for, (b) if we try to open a text file, (c) if we try to open a text file, (d) All of the above, , G, , 25. Which of the following about a dictionary is false?, (a) Dictionary can be defined by enclosing a comma-separated list of key-value pairs in curly braces ({})., (b) A colon (:) separates each key from its associated value., (c) Dictionary is immutable., (d) The values of a dictionary can be of any type., , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 141
Page 149 :
SECTION - B, This section consists of 24 Questions (26 to 49). Attempt any 20 questions., for i in range(1,10,3):, print(i,sep=”-”,end=”*”), , (a) 1-4-7*, , (b) 1-4-7-10*, , (c) 1*4*7*, , 27. Suppose content of ‘Myfile.txt’ is:, Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, What will be the output of the following code?, , he, , (b) [30], , (b) How I wonder what you are, (d) How I wonder what you are, Up above the world so high, Like a diamond in the sky, , rs, , (a) Twinkle twinkle little star, (c) Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, 28. L=[10,20,30,40,50], print(L[2:-2]), (a) [30,40], , (d) 1*4*7*10, , Pr, ak, , f = open(“Myfile.txt”), data=f.readline(), data=f.read(), print(data), f.close(), , as, ha, n, , 26. Give the output, , (c) [20,30,40], , (d) [40], , K=5, L=36, while K<=L:, K+=6, , (a) 4, , ot, , 29. How many times does the following while loop get executed?, , (c) 6., , (b) 4,9, , (c) 5,9, , (b) 5, , (d) 7, , 30. What will be displayed after the execution of the following loop?, , Br, , sum,last=0,10, for C in range(1,last,2):, sum=sum+1;, print(sum,C), , (d) 4,10, , al, , (a) 5,10, , oy, , 31. Choose correct option to sort items in a list lt in descending order., (a) lt.sort(desc), (b) lt.sort(descending), (c) lt.sort(reverse=True), (d) it.sort(descending=True), , G, , 32. Rahal is trying to read data from a binary file test.bin and store it into List L. Consider the following code, written by him., , 142, , import pickle as p, with open(‘test’,’rb’) as f:, _________________, , Identify the missing code in Statement 1., (a) f=p.load(L), (b) p=p.load(L), , #statement 1, , (c) L=p.load(f), , (d) f=L.load(p), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 150 :
33., , , , , The binary file STOCK.DAT is containing following fields, SName and Price, Function Billing() is created in Python to read each record of a pickled file STOCK.DAT, and display the, Total Price of all the records in the file., , as, ha, n, , import pickle, def Billing():, , file=open(‘STOCK.DAT’,’rb’), , IRec=pickle.load(file) #To read the object from file, , Totprice=0, , for I in IRec:, , ___________, , print (Totprice), , file.close(), , Choose appropriate statement to calculate the total price from the following:, (a) Totprice=I[1], (b) Totprice=+I[1], (c) Totprice+=I[1], , Pr, ak, , 34. Give the output, print(“hi”), , (d) Totprice=I+Totprice, , def abc():, , print(“hello”), print(“bye”), abc(), , (a) hi, (b) hi, (c) hello, (d) bye, hello bye bye hello, bye hello hi hi, , rs, , 35. Evaluate the following expression and identify the correct answer., c = 25-5*4/2-10+5, (a) 10.0, (b) 35.0, (c) -2.5, , (d) -12.5, , (a) 0, , ot, , while x>1:, , x=x//3, , x=x+1, print(x), , he, , 36. What will be the final value of variable x after the following code is executed:, , x=10, , (b) 1, , (c) 2, , (d) 3, , (c) 5#5, , (d) 5#10, , Br, , 37. What will be the output of the following code?, , al, , def fun():, , global a, , a=10, , print(a,end=”#”), a=5, fun(), print(a), , oy, , (a) 10#5, , (b) 10#10, , 38. What are the possible outcome(s) executed from the following code?, , G, , import random, PLAY=[40,50,10,20], ROUND=random.randint(2,3), for J in range(ROUND,1,-1):, print (PLAY[J],”:”,end=””), , (a) 20:10:, , (b) 20:10:50:, , (c) 20:, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , (d) 40:50:20:, 143
Page 152 :
as, ha, n, , 43. Which of the following options can be used to read the last line of a text file?, (a) file=f.readlines() , (b) file=f.readline(-1), print(file[-1]) print(file), (c) file=f.read() , (d) file=f.read(-1), print(file[-1]) print(file), 44. Study the following program and select the possible output(s) from the options (a) to (d) following it., , import random, X=random.random(), Y=random.randint(0,4), print (int(X),”:”,Y+int(X)), , (ii) 1:6, (iv) 0:3, (b) (ii) and (iii), , (c) (iii) and (iv), , 45. In f=open(“abc.txt”,”w”), ‘w’ refers to, (a) file name, (b) file object, , (c) file access mode, , (d) (i) and (iv), , (d) file pointer, , Pr, ak, , (i) 0: 0, (iii) 2:4, (a) (i) and (ii), , 46. When the function ABLINES() is executed, it read contents from a text file LINES.TXT, to display those lines,, which are either starting with an alphabet ‘A’ or starting with alphabet ‘B’., , #statement 1, , rs, , def ABLINES():, file=open(‘LINES.TXT’,’r’), , lines = file.readlines(), , for w in lines:, , if _______________:, , print (w), , file.close(), , , 47. Give the output, , f=open(‘C:\\abc.txt’,’r’), f.seek(10), f.seek(5), k=f.tell(), print(k), , (a) 5, , Br, , , , , , , , al, , 48. EOL stands for, (a) End of Line, , (d) (ii) and (iii), , ot, , he, , Select the appropriate statement to fill the statement 1., (i) w[0]= =”A” or w[0]= =”B”, (ii) w[0] in [“A”,”B”], (iii) w[0]= =”A” and w[0]= =”B”, (iv) w[0]= =”A”,”B”, (a) (i) and (ii), (b) (ii) and (iv), (c) (i) and (iv), , (b) 0, , (c) 5, , (d) 4, , (b) End of List, , (c) End of Lists, , (d) None of these, , (c) [11,5,6], , (d) [“two’,”three”], , oy, , 49. Give the output, , G, , , , , , , , , lt=[1,0,5,8,10,15], lt2=[[‘one’,’two’,’three’],[4,5,6]], lt[2]=lt[3], lt[0]=lt[1], lt2[-1][0]=lt[2]+3, print(lt2[1]), , (a) [“two”], , (b) [4,5,6], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 145
Page 153 :
SECTION - C, Case Study Based Questions., This section consists of 6 Questions (50-55). Attempt any 5 questions., , Pr, ak, , import csv, def CSVOpen():, with open(‘_______’,’’w’,newline=’’) as csvf:, cw=______, ______, cw.writerow([‘Rapunzel’,’Jack’,300]), cw.writerow([‘Barbie’,’Doll’,900]), cw.writerow([‘Johnny’,’Jane’,280]), , as, ha, n, , Amit Shah is a programmer, who has recently been given a task to write a python code to perform the following, CSV file operations with the help of two user defined functions/modules:, (a) CSVOpen() : to create a CSV file called BOOKS.CSV in append mode containing information of books –, Title, Author and Price., (b) CSVRead() : to display the records from the CSV file called BOOKS.CSV where the field title ends with, ‘G’., He has succeeded in writing partial code and has missed out certain statements, so he has left certain queries in, comment lines., , Br, , ot, , he, , rs, , def CSVRead():, try:, with open(‘books.csv’,’r’) as csvf:, cr=______, for r in cr:, if ______:, print(r), except:, print(‘File Not Found’), ___________, CSVRead(), , #Statement-1, #Statement-2, #Statement-3, , #Statement-4, #Statement-5, , #Statement-6, , You as an expert of Python have to provide the missing statements and other related queries based on the following, code of Amit., , al, , 50. Choose the appropriate file name to be opened in append mode (Statement 1)., (a) books.csv, (b) books-csv, (c) books[csv], , (d) books_csv, , oy, , 51. Which statement will be used to create a csv writer object in Statement 2., (a) csvwriter(csvf), (b) csv.writer(csvf), (c) csv[writer](csvf), (d) csv_writer(csvf), , G, , 52. Choose the correct option for Statement 3 to write the names of the column headings in the CSV file, BOOKS., CSV., (a) cw.writerow({‘Title’,’Author’,’Price’}), (b) cw.writerow([‘Title’,’Author’,’Price’]), (c) cw.writerows(‘Title’,’Author’,’Price’), (d) cw.write([‘Title’,’Author’,’Price’]), , 146, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 154 :
53. Which statement will be used to read a csv file in Statement 4., (a) csvread(csvf) , , (b) csv.reader(csvf), , (c) csv_reader(csvf) , , (d) csvf.reader(cs), , (b) r[-1][0]==’G’, , (a) r[0][-1]==’G’, , (c) r[-1][-1]==’G’, , 55. Which statement will be used to call function CSVOpen() in Statement 4., , as, ha, n, , 54. Fill in the appropriate statement to check the field Title ending with ‘G’ for Statement 5 in the above program., , (a) call CSVOpen() , , (b) csvf.CSVOpen(), , (c) CSVOpen() , , (d) csvf[CSVOpen], , Answers (Model Test Paper – 2), 3. (c), 13. (d), , 4. (b), 14. (b), , 5. (d), 15. (d), , 21. (d), 31. (c), 41. (a), , 22. (a), 32. (c), 42. (c), , 23. (d), 33. (c), 43. (a), , 24. (a), 34. (b), 44. (d), , 25. (c), 35. (a), 45. (c), , 51. (b), , 52. (b), , 53. (b), , 54. (a), , 55. (c), , 6. (b), 16. (b), , 7. (d), 17. (a), , 26. (c), 36. (b), 46. (a), , 27. (d), 37. (b), 47. (a), , 8. (b), 18. (a), , 9. (d), 19. (c), , 10. (d), 20. (a), , 28. (b), 38. (a), 48. (a), , 29. (c), 39. (b), 49. (c), , 30. (c), 40. (b), 50. (a), , Pr, ak, , 2. (d), 12. (a), , G, , oy, , al, , Br, , ot, , he, , rs, , 1. (a), 11. (b), , (d) r[0][0]==’G’, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 147
Page 155 :
MODEL TEST PAPER – 3, , (Based on the Latest CBSE Sample Paper), Time Allowed : 90 Minutes, , as, ha, n, , Maximum Marks : 35, , General Instructions :, 1. The question paper is divided into 3 Sections - A, B, and C., 2. Section A consists of 25 Questions (1-25). Attempt any 20 questions., 3. Section B consists of 24 Questions (26-49). Attempt any 20 questions., 4. Section C consists of 6 case study based Questions (50-55). Attempt any 5 questions., 5. All questions carry equal marks., , Pr, ak, , SECTION - A, , This section consists of 25 Questions (1 to 25). Attempt any 20 questions from this section. Choose the best, possible option., 1. Identify invalid variable names out of the following., (a) for, (b) _salary, , (c) salary12, , 2. Consider a declaration L = “15.6”, Which of the following represents the data type of L?, (a) list, (b) tuple, (c) float, , (d) product, , (d) string, , he, , rs, , 3. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90)., What will be the output of print(t[::])?, (a) no output, (b) error message, (c) (10, 20, 30, 40, 50, 60, 70, 80, 90), (d) (10), 4. Which of the following options is correct?, (a) The default mode in text file is r, (c) The default mode in text file is w, , (b) The default mode in text file is r+, (d) The default mode in text file is rw, , Br, , ot, , 5. Which of the following options can be used to read at most n number of bytes, does not read more than one, line?, (a) myfile = open(‘Myfile.txt’); myfile.read(), (b) myfile = open(‘Myfile.txt’,’r’); myfile.read(n), (c) myfile = open(‘Myfile.txt’); myfile.readline(n), (d) myfile = open(‘Myfile.txt’); myfile.readlines(), , al, , 6. Assume that the position of the file pointer is at the beginning of 3rd line in a text file. Which of the following, options can be used to read from the beginning of the file?, (a) myfile.read(), (b) myfile.readline(), (c) myfile.readlines(), (d) None of the above, , G, , oy, , 7. Identify the correct option out of the following options to open the binary file in read mode., (a) myfile = open(‘student’,’rb’), (b) myfile = open(‘student’,’r+b’), (c) myfile = open(‘student’,’br’), (d) all of the above, , 148, , 8. Choose the correct function Name to check if a string contains only alphabets, (a) alpha(), (b) toalpha, (c) isalpha(), , (d) ifalpha(), , 9. Which is not a valid string?, (a) ‘50’, (b) “50”, , (d) 50, , (c) ‘‘‘50’’’, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 156 :
10. Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is incorrect?, (a) len(T), (b) count(T), (c) del T, (d) max(T), (d) All of the above, , 12. tell() method takes _______________ parameter(s)., (a) 0, (b) 1, , (d) 3, , (c) 2, , as, ha, n, , 11. Which type of file stores the data in the same way as stored in the memory?, (a) Text, (b) Binary, (c) CSV, , 13. Which statement is correct to open binary file for writing?, (a) f.open(“file”,wb) , (b) f=open(“file”,w+b), (c) open(f=”file”,bw) , (d) f[open(“file”,wb)], , 14. In seek(), value _______________ sets the reference point at the end of the file., (a) 0, (b) 1, (c) 2, 15. Creating your own function is called, (a) own-defined function , (c) user-defined function , , (d) 3, , Pr, ak, , (b) in-built function, (d) all-defined function, , 16. Which of the following function header is incorrect?, (a) def xyz(x,y,z) , (c) def xyz(x=5,y=30,z) , , (b) def xyz(x=5,y=30,z=20), (d) def xyz(x,y=30,z=20), , (d) func(15,b=20), , 18. CSV file can be created in, (a) excel, (b) notepad, , (d) all of the above, , rs, , 17. Which of the following is the incorrect way to call a function?, (a) func(15,20), (b) func(a,b), (c) func(), , (c) wordpad, , he, , 19. Which one is correct option to read csv file from file object f ?, (a) reader(f), (b) f.reader, (c) reader.f, , ot, , 20. What is the correct expansion of CSV files?, (a) Comma Separated Values , (c) Common Separated Values , , (d) reader[f], , (b) Comma Separated Valve, (d) Common Separation Values, , Br, , 21. Which of the following options is correct?, (a) Open a file for writing only in binary file in wb mode, (b) if we try to open a binary file in wb mode that exists, overwrites the file, (c) if we try to open a binary file in wb mode that does not exist, the file gets Created., (d) All of the above, , al, , 22. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90), What will be the output of print(t[-1:-4])?, (a) (90,80,70,60), (b) (60,70,80,90), (c) (90,80,70), , (d) ( ), (d) Dictionary, , 24. The file pointer is placed at the end of the file when the file is opened in, (a) r mode, (b) w mode, (c) a mode, , (d) all of the above, , G, , oy, , 23. Choose the correct name of the immutable data object from the following:, (a) List, (b) Set, (c) Tuple, , 25. Which is the correct form of declaration of dictionary?, (a) Day={1:’monday’,2:’tuesday’,3:’wednesday’}, (b) Day=(1;’monday’,2;’tuesday’,3;’wednesday’), (c) Day=[1:’monday’,2:’tuesday’,3:’wednesday’], (d) Day={1’monday’,2’tuesday’,3’wednesday’], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 149
Page 157 :
SECTION - B, This section consists of 24 Questions (26 to 49). Attempt any 20 questions., name=”ComputerSciencewithPython”, print(name[3:10]), , (a) mputerS, , (b) puterSc, , (c) mputerScie, , 27. Suppose content of ‘Myfile.txt’ is:, Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, What will be the output of the following code?, , lt=[22,25], L.append(lt), print(L), , (a) [10,20,30,40,22,25], (c) [10,20,30,40,[22,25]], , he, , 28. L=[10,20,30,40], , (b) How I wonder what you are, (d) How I wonder what you are, Up above the world so high, Like a diamond in the sky, , rs, , (a) Twinkle twinkle little star, (c) Twinkle twinkle little star, How I wonder what you are, Up above the world so high, Like a diamond in the sky, , (d) puterScien, , Pr, ak, , f = open(“Myfile.txt”), data=f.readline(), data=f.readlines(), for row in data:, print(row,end=””), f.close(), , as, ha, n, , 26. What will be the output of the following code?, , (b) [10,20,22,25,30,40], (d) [10,20,[22,25],30,40], , ot, , 29. How many times will the loop execute?, , (a) 3, , Br, , value1,value2=7,19;, while value1<=value2:, value1=value1+2, value2=value2-2, , (b) 4, , (c) 5, , (d) 6, , 30. What will be the values of variables ‘P’ and ‘Q’ after the execution of the following code?, , oy, , al, , Q=0;, for P in range(1,5,1):, Q+=P, Q=Q-1, print(P,Q), , (a) 5,6, , (b) 5,5, , (c) 4,6, , G, , 31. Write a command to show the contents of list lt in reverse order., (a) lt.revorder(), (b) it.rev_order(), (c) it.reverse_order(), , (d) 4,5, (d) it.reverse(), , 32. Manoj is trying to open binary file to write data but facing some problems. Select the correct option to open the, file “STUDENT.DAT” for writing only in binary format, (a) F= open(“STUDENT.DAT”,’wb’), (b) F= open(“STUDENT.DAT”,’w’), (c) F= open(“STUDENT.DAT”,’wb+’), (d) F= open(“STUDENT.DAT”,’w+’), , 150, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 158 :
33. When function SPLDOCS() is executed, it display all the content from a pickled file DOCS.DAT, where, Specialisation of DOCTORS is “CARDIOLOGY”., , (d) Disp[D], , Pr, ak, , To fill the missing statement 1, choose the statement to call function Disp, (a) D[Disp()], (b) D.Disp(), (c) Disp(D), 34. What will be the output of the following Python code?, , as, ha, n, , def Disp(s):, , print (s.Name,”#”,s.Specialisation), def SPLDOCS():, , D=DOCTORS(), , file=open(‘DOCS.DAT’,’rb’), , try:, , while True:, , D=pickle.load(file), , if D.Specialisation == ‘CARDIOLOGY’:, , ________, , except EOFError:, , pass, , file.close(), , def abc():, , print(“hello”), print(“hi”), print(“bye”), abc(), , he, , rs, , (a) hi, (b) hi, (c) hello, (d) bye, hello bye hi hello , bye hello bye hi, 35. Evaluate the following expression and identify the correct answer., a=20*5+3**2%2//5, (a) 101, (b) 100, (c) 1.9, (d) -100, 36. What will be the output of the following code?, , ot, , def my_func(var1=100, var2=200):, var1+=10, var2 = var2 - 10, return var1+var2, print(my_func(50),my_func(20,30)), , (c) 250 50, , (d) 250 300, , Br, , (a) 100 200, (b) 150 300, 37. Write the output of the following Python code:, , al, , def Update(X=10):, , X += 15, , print( X,end=”#”), X=20, Update(), print(X), , (d) 25#25, , oy, , (a) 25#20, (b) 20#25, (c) 20#20, 38. What are the possible outcome(s) executed from the following code?, , G, , import random, SIDES=[“EAST”,”WEST”,”NORTH”,”SOUTH”];, N=random.randint(1,3), OUT=””, for I in range(N,1,-1):, , OUT=OUT+SIDES[I], print (OUT), , (a) SOUTHNORTH , (c) SOUTH , , (b) SOUTHNORTHWEST, (d) EASTWESTNORTH, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 151
Page 159 :
(a) 91.0,12.0,35.0,44.0, , (c) 41.0,32.0,15.0,94.0, , , (b) 32.0,15.0,94.0,41.0, (d) 90.0,100.0,130.0,170.0,, , 40. Suppose content of ‘Myfile.txt’ is, , What will be the output of the following code?, , myfile = open(“Myfile.txt”), record = myfile.readline(2).split(), print(len(record)), myfile.close(), , (a) 1, , (b) 2, , 41. Give the output, , Pr, ak, , Stay positive and happy, Work hard and don’t give up hope, Be open to criticism and keep learning, Surround yourself with happy, warm and, genuine people, , , , , , as, ha, n, , 39. What is the output of the following code snippet?, , STR = [‘90’,’10’,’30’,’40’], COUNT = 3, SUM = 0, for I in [1,2,5,4]:, S = STR[COUNT], SUM = float (S)+I, print (SUM,end=”,”), COUNT-=1, , (c) 7, , Br, , ot, , he, , rs, , def makenew(mystr):, , newstr = “ “, , count = 0, , for, i in mystr:, , if count%2!=0:, , newstr= newstr+str(count), , elif i.islower():, , newstr=newstr+i.upper(), , else:, , newstr=newstr+i, , count+=1, , newstr = newstr+mystr[:1], , print (newstr), makenew(“sTUdeNT”), , (d) 11, , (a) 1T3D5N71, , (b) S1U3E5Ts, , (c) S1UDE7Ts, , (d) STUDENTS, , 42. Suppose content of ‘Myfile.txt’ is, , al, , Honesty is the best policy., Be Honest., , oy, , What will be the output of the following code?, myfile = open(“Myfile.txt”), , G, , x = myfile.readline(35), print(len(x)), myfile.close(), , (a) 28, , (b) 30, , (c) 35, , (d) 38, , 43. Which of the following options can be used to read the last character of a text file?, (a) file=f.readline(), (b) file=f.readlines(), (c) file=f.read(-1), (d) file=f.read(), print(file[-1]) print(file[-1]) print(file) print(file[-1]), 152, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 160 :
import random, PICK=random.randint(0,3), CITY=[“DELHI”,”MUMBAI”,”CHENNAI”,”KOLKATA”], for I in CITY:, , for J in range(1,PICK):, , print(I,end=””), , print(), , (iii), , DELHI, MUMBAIMUMBAI, KOLKATAKOLKATAKOLKATA, , (b) (ii) and (iv), , (c) file access mode, , (d) (i) and (iii), , (d) function, , he, , File = open(“Mydata”,”a”), , (c) (iii) only, , rs, , 45. In f=open(“abc.txt”,”w”), “abc.txt” refers to, (a) file name, (b) file object, 46. Observe the following code, , DELHI, DELHIMUMBAI, DELHIMUMBAICHENNAI, (iv), , DELHI, MUMBAI, CHENNAI, KOLKATA, (a) (i) only, , (ii), , Pr, ak, , (i), DELHIDELHI, MUMBAIMUMBAI, CHENNAICHENNAI, KOLKATAKOLKATA, , as, ha, n, , 44. What are the possible outcome(s) executed from the following code?, , _____________________ #Blank1, File.close(), , ot, , Fill the Blank 1 with statement to write “ABC” in the file “Mydata”., (a) File.write(“ABC”) , , (b) File.writelines(“ABC”), , (c) File.writedata(“ABC”) , , (d) File.writes(“ABC”), , oy, , al, , Br, , 47. A folder Test is created in root directory C:\. Two subfolders test1 ,test2 and one “x.txt”, is created in Test Folder. “y.txt” and “Try.py” are created in folder Test1 and “z.txt” is, created in Test2., Choose the incorrect option to write single line statement in “Try.py” to open the, “y.txt” file which is stored in same parent folder Test1 using relative path., (a) f=open(“y.txt”) , (b) f=open(“.\y.txt”), (c) f=open(“..\\test1\y.txt”) , (d) f=open(“test1\y.txt”), 48. Which command is used to move the file pointer at 5 position in text file., (a) f.tell(5), (b) f.position(5), (c) f.seek(5), , C:\, , Test, x.txt, Test 1, y.txt, , Test 2, , try.py, , z.txt, , (d) f.pointer(5), , 49. Give the output, , G, , L=[10,20,30,40,50], L[1:3]=45,67, print(L), , (a) [10, 45, 67, 40, 50], , (b) [45, 67, 40, 50], , (c) [45, 67], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , (d) [10, 45, 67, 50], 153
Page 161 :
SECTION - C, Case Study Based Questions., This section consists of 6 Questions (50-55). Attempt any 5 questions., , as, ha, n, , Your teacher has given you a method/function FilterWords() in python which read lines from a text file NewsLetter., TXT, and display those words, which are lesser than 4 characters. Your teachers intentionally kept few blanks in, between the code and asked you to fill the blanks so that the code will run to find desired result. Do the needful with, the following python code., def FilterWords():, c=0, file=open(‘NewsLetter.TXT’, ‘_____’), line = file._____, word = _____, for c in word:, if _____:, print(c), _________, , 50. Write mode of opening the file in statement-1?, (a) a, (b) ab, , #Statement-4, , Pr, ak, , __________, , #Statement-1, #Statement-2, #Statement-3, , #Statement-5, #Statement-6, , (c) w, , (d) r, , (d) readlines( ), , 52. Fill in the blank in statement-3 to read data word by word., (a) line.Split(“word”), (b) line.split(“w”), (c) line.split(), , (d) split(line), , rs, , 51. Fill in the blank in statement-2 to read the data from the file., (a) File.Read(), (b) read(), (c) read.lines( ), , he, , 53. Fill in the blank in statement-4, which display the word having lesser than 4 characters., (a) length(c) <4, (b) len(c)<4, (c) c.len ( )<4, (d) len [c ]<3, 54. Fill in the blank in Statement-5 to close the file., (a) file.close(), (b) Close(file), , (c) file.Close(), , (d) close(file), , ot, , 55. Fill in the blank in Statement-6 to call the function FilterWords()., (a) call FilterWords(), (b) def FilterWords(), (c) FilterWords(), , (d) file FilterWords(), , 2. (d), 12. (a), , 3. (c), 13. (b), , 4. (a), 14. (c), , 5. (c), 15. (c), , 6. (d), 16. (c), , 7. (d), 17. (d), , 8. (c), 18. (d), , 9. (d), 19. (a), , 10. (b), 20. (a), , 21. (d), 31. (d), 41. (b), , 22. (d), 32. (a), 42. (a), , 23. (c), 33. (c), 43. (d), , 24. (c), 34. (b), 44. (d), , 25. (a), 35. (b), 45. (a), , 26. (a), 36. (c), 46. (a), , 27. (d), 37. (a), 47. (d), , 28. (c), 38. (a), 48. (c), , 29. (b), 39. (c), 49. (a), , 30. (c), 40. (a), 50. (d), , 51. (b), , 52. (c), , 53. (b), , 54. (a), , 55. (c), , G, , oy, , al, , 1. (a), 11. (b), , Br, , Answers (Model Test Paper – 3), , 154, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 162 :
MODEL TEST PAPER – 4, , (Based on the Latest CBSE Sample Paper), Time Allowed : 90 Minutes, , as, ha, n, , Maximum Marks : 35, , General Instructions :, 1. The question paper is divided into 3 Sections - A, B, and C., 2. Section A consists of 25 Questions (1-25). Attempt any 20 questions., 3. Section B consists of 24 Questions (26-49). Attempt any 20 questions., 4. Section C consists of 6 case study based Questions (50-55). Attempt any 5 questions., 5. All questions carry equal marks., , Pr, ak, , SECTION - A, , This section consists of 25 Questions (1 to 25). Attempt any 20 questions from this section. Choose the best, possible option., 1. Identify invalid variable name(s) out of the following., (a) While, (b) 123salary, (c) Big, , (d) Product, , 2. Consider a declaration L = 1, ‘Python’, ‘3.14’, Which of the following represents the data type of L?, (a) list, (b) tuple, (c) float, , (d) string, , he, , rs, , 3. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90)., What will be the output of print(t[::1])?, (a) no output, (b) error message, (c) (10, 20, 30, 40, 50, 60, 70, 80, 90), (d) (10,30,50,70,90), , ot, , 4. Which of the following options is correct?, (a) Opening file in rb mode means opened a file for reading only in binary format., (b) Opening file in rb mode, the file pointer is placed at the beginning of the file., (c) rb mode is the default mode in binary file., (d) All are correct, , Br, , 5. Which of the following options can be used to read at most n number of bytes, can read more than one line?, (a) myfile = open(‘Myfile.txt’); myfile.read(), (b) myfile = open(‘Myfile.txt’,’r’); myfile.read(n), (c) myfile = open(‘Myfile.txt’); myfile.readline(n), (d) myfile = open(‘Myfile.txt’); myfile.readlines(), 6. Which one is correct option to close the file?, (a) f.close, (b) f.close(), , (c) f(close), , (d) close(f), , oy, , al, , 7. Identify the correct option out of the following options to open the binary file for reading and writing both., (i) myfile = open(‘student’,’rb+’), (ii) myfile = open(‘student’,’wb+’), (iii) myfile = open(‘student’,’rwb’), (iv) myfile = open(‘student’,rb+wb+), (a) only (i), (b) both (i) and (iv), (c) both (iii) and (iv), (d) both (i) and (ii), , G, , 8. Choose the correct function name required to check if a string contains only lowercase letters., (a) islower(), (b) lower(), (c) tolower(), (d) onlylower(), 9. The expression “5”*3 will return, (a) ‘15’, (b) 15, , (c) ’555’, , (d) error, , 10 Suppose a tuple T is declared as T = (10, 12, 43, 39), which of the following is correct?, (a) T.append(2), (b) T.pop(), (c) T.count(10), (d) T.drop(43), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 155
Page 163 :
11. _______________ function is used to write in pickle file., (a) write, (b) dump, (c) store, , (d) pick, , 12. tell() method returns _______________ data type., (a) integer, (b) string, , (d) float, , (c) boolean, , 14. Which statement is not valid?, (a) f.seek(0,2), (b) f.seek(2,0), , (c) f.seek(1,3), , as, ha, n, , 13. Which statetment is correct to unpickle data into list where a is file object, b pickle object and c is the name of, list?, (a) c=b.load(a), (b) a=b.load(c), (c) b=a.load(b), (d) a=c.load(b), (d) f.seek(3,1), , 15. The list of identifiers used in a function call is called, (a) actual parameter(s) , (b) formal parameter(s), (c) value parameter(s) , (d) type parameter(s), , (b) def prt(p=100, r=8, t), (d) def prt(p, r=8, t=2), , Pr, ak, , 16. Which of the following function header is correct?, (a) def prt(p=100, r, t=2) , (c) def prt(p, r=8, t) , , 17. Which of the following is the incorrect way to call a function?, (a) func(10,20) , (b) func(a=10,b=20), (c) func(b=20,a=10) , (d) func(10,b=20), 18. CSV file can be opened in, (a) excel, (b) notepad, , (c) wordpad, , (d) all of these, (d) writerows(), , 20. Which of the following is not a function/method of csv module in Python?, (a) write(), (b) reader(), (c) writer(), , (d) writerow(), , he, , rs, , 19. _______________ method takes 1-dimensional data (one row) to write in csv., (a) writedata(), (b) writeone(), (c) writerow(), , ot, , 21. Which of the following options is not correct?, (a) if we try to open text file in r mode that does not exist, an error occurs., (b) if we try to open file in w mode that does not exist, the file gets created., (c) if we try to open file in r+ mode that does not exist, no error occurs., (d) if we try to open file in w+ mode that does not exist, the file gets created., , Br, , 22. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90), What will be the output of print(t[-1:-4:-1])?, (a) (90,80,70,60), (b) (60,70,80,90), (c) (90,80,70), , (d) ( ), (d) List, , 24. The file pointer is placed at the end of the file when the file is opened in, (a) a mode, (b) ab mode, (c) a+ mode, , (d) all of these, , oy, , al, , 23. Choose the correct name of the mutable data object from the following:, (a) Int, (b) Tuple, (c) String, , G, , 25. What will happen when new key is same as one of the existing keys in dictionary?, (a) It will overwrite the new value with the old value of the same key., (b) New value will be added at the end., (c) Error message will be raised., (d) New value will be merged with old one under existing key., , 156, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 164 :
SECTION - B, This section consists of 24 Questions (26 to 49). Attempt any 20 questions., m = 16, m = m+1, if m<15:, print(m), else:, print(m+15), , (a) 32, , (b) 16, , (c) 17, , 27. Suppose content of ‘abc.txt’ is:, India is Great, I love my India, f=open(‘abc.txt’,’r’), data=f.readline(), print(len(data)), f.close(), , (a) 11, , (b) 12, , (c) 14, , 28. L=[10,20,30,40], , (d) 15, , rs, , lt=[22,25], L.extend(lt), print(L), , (d) 31, , Pr, ak, , What will be the output of the following code?, , as, ha, n, , 26. Give the output, , (a) [10,20,30,40,22,25], (c) [10,20,30,40,[22,25]], , (b) [10,20,22,25,30,40], (d) [10,20,[22,25],30,40], , he, , 29. How many times will the following WHILE loop execute and what will be the value of sum after execution, the following loop?, , loop, loop, loop, loop, , will, will, will, will, , be, be, be, be, , executed, executed, executed, executed, , 4, 5, 6, 7, , times, times, times, times, , and, and, and, and, , Br, , (a), (b), (c), (d), , ot, , y,sum=7,0, while y<=15:, sum = sum + y, y = y+2, print(sum), , value, value, value, value, , of, of, of, of, , sum, sum, sum, sum, , is, is, is, is, , 53, 55, 57, 59, , al, , 30. What will be the values of variables ‘m’ and ‘n’ after the execution of the following code?, , oy, , n=5;, for m in range(5,10,1):, n+=m, n=n-1, print(n,m), , (a) 25 10, , (b) 35 9, , (c) 25 9, , (d) 35 10, , (c) -3, , (d) -2, , G, , 31. Give the output, , lt=[9,8,6,5,4,3,2,0], print(lt.index(3)), , (a) 5, , (b) 3, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 157
Page 165 :
as, ha, n, , 32. Which of the following statement(s) is/are correct regarding the file access modes?, (a) ‘r+’ opens a file for both reading and writing. File object points to its beginning., (b) ‘w+’ opens a file for both writing and reading. Adds at the end of the existing file if it exists and creates, a new one if it does not exist., (c) ‘wb’ opens a file for reading and writing in binary format. Overwrites the file if it exists and creates a, new one if it does not exist., (d) ‘a’ opens a file for appending. The file pointer is at the start of the file if the file exists., 33. Function GetStudents() is created to calculate the no of students those have scored more than 75 percentage., import pickle, , rs, , Pr, ak, , def GetStudents():, , Countabove75=0, , with open(“STUDENT.DAT”,”rb”) as F:, , while True:, , try:, , ____________ #1 statement to read from the file, , , if R[2] > 75:, , print(R[1], “ has percent = “,R[2]), , Countabove75+=1, , except:, , break, , , if Countabove75==0:, , print(“There is no student who has percentage more than 75”), , else:, , print(“no of students who has percentage mroe than 75 = “,Countabove75), , Which of the following commands is used to read each record from the binary file STUDENT.DAT? (marked, as #1 in the Python code?, (b) pickle.read(r,f), , 34. Give the output, def abc(a=2,b=4):, return a+b, , x=10, y=20, , Br, , x=abc(x,y), , (c) r= pickle.read(f), , (d) pickle.load(r,f), , (c) 30,4, , (d) 6,4, , ot, , , , he, , (a) R = pickle.load(F), , print(x,y), , (a) 30,20, , (b) 6,20, , al, , 35. Evaluate the following expression and identify the correct answer., x=10 > 5 and 7 > 12 or not 18 > 3, , (a) True, , (b) False, , (c) 0, , (d) 1, , (c) 300 290, , (d) 250 300, , oy, , 36. What will be the output of the following code?, , def my_func(var1=100, var2=200):, , , G, , , , , var1+=10, , var2 = var2 - 10, return var1+var2, , print(my_func(),my_func(20,30)), , 158, , (a) 300 300, , (b) 300 50, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 166 :
37. What will be the output of the following code?, value = 50, , , global value, , , , if value/5==5:, , , , , , , , value = 25, , else:, , value = value + N, value = value - N, , print(value, end=’#’), display(20), , print(value), , (a) 50#45, , (b) 50#5, , (c) 5#45, , as, ha, n, , def display(N):, , (d) 5#50, , import random, , X =[100,75,10,125], , Go = random.randint(0,3), for i in range(Go):, , , print (X[i],”$$”,end=””), , (c) 75$$10$$ , , (b) 75$$10$$125$$, , rs, , (a) 100$$75$$10$$ , , Pr, ak, , 38. Observe the following Python code and find out which out of the given options (a) to (d) are the expected, correct output(s)., , (d) 10$$125$$100, , 39. What is the output of the following code snippet?, , he, , L1 = [100,900,300,400,500], START = 1, SUM = 0, , , ot, , for C in range (START,4):, SUM = SUM + L1[C], , print (C,’:’,SUM), , (b) 3:1600, , Br, , (a) 4:1600, , (c) 4:2100, , (d) 3:2100, , al, , 40. Suppose content of ‘Myfile.txt’ is, Stay positive and happy, Work hard and don’t give up hope, Be open to criticism and keep learning, Surround yourself with happy, warm and genuine people, , oy, , What will be the output of the following code?, , myfile = open(“Myfile.txt”), record = myfile.readlines(), , G, , rec=record[2].split(), print(len(rec)), myfile.close(), , (a) 1, , (b) 2, , (c) 7, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , (d) 11, 159
Page 167 :
41. Find and write the output of the following python code:, , (a) ISSCE *3129, , (b) ISSCE*3129, , (b) Mind@*Wrk*, , ot, , (a) Mnd@*Wrk!*, , he, , Text=”Mind@Work!”, T=””, c=0, for i in Text:, , if not i.isalpha():, , T=T+”*”, , elif not i.isupper():, , T=T+(Text[c+1]), , else:, , T=T+i.upper(), , c=c+1, print(T), , (c) AISSC*3129, , (d) ISSCE *018, , rs, , 42. Give the output, , Pr, ak, , as, ha, n, , Text1=”AISSCE 2018”, #space between AISSCE and 2018, Text2=””, I=0, while I<len(Text1):, , if Text1[I]>=”0” and Text1[I]<=”9”:, , Val = int(Text1[I]), , Val = Val + 1, , Text2=Text2 + str(Val), , elif Text1[I]>=”A” and Text1[I] <=”Z”:, , Text2=Text2 + (Text1[I+1]), , else:, , Text2=Text2 + “*”, , I=I+1, print (Text2), , Br, , 43. Which of the following is not a file access mode?, (a) rb, (b) rb+, , (c) Mid@*Wrk!*, , (d) Min@Work!*, , (c) wb, , (d) rw, , 44. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from, the following code?, , G, , oy, , al, , import random, POINTS=[30,50,20,40,45];, BEGIN=random.randint(1,3), LAST=random.randint(2,4), for C in range(BEGIN,LAST+1):, print (POINTS[C],”#”,end=””), , (a) (i) and (ii), , (i), (ii), (iii), (iv), 20#50#30# 20#40#45# 50#20#40# 30#50#20#, (b) (ii) and (iii), , 45. In f=open(“abc.txt”,”w”), open() refers to, (a) file name, (b) file object, , 160, , (c) (iii) and (iv), , (d) (i) and (iv), , (c) file access mode, , (d) function, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 168 :
46. When SHORTWORDS() is executed it read lines from a text file WORDBANK.TXT and display those words,, which are lesser than 5 characters., def SHORTWORDS():, file=open(‘WORKBANK.TXT’,’r’), line = file.read(), , word = line.split(), for w in word:, , if ________: # statement 1, print (w), , file.close(), , Select the appropriate statement to fill the statement 1., (a) len[w]<5, , (b) w.length()<5, , (c) w.len()<5, , as, ha, n, , c=0, , (d) len(w)<5, , C:\, , Choose the correct option to write single line statement in “Try.py” to open the, “z.txt” file which is stored in folder Test2 using relative path, , Test, , Pr, ak, , 47. A folder Test is created in root directory C:\. Two subfolders test1, test2 and one, “x.txt” is created in Test Folder. “y.txt” and “Try.py” are created in folder Test1 and, “z.txt” is created in Test2., , (a) f=open(“..\\test2\z.txt”), , (b) f=open(“test2\z.txt”), , Test 1, , Test 2, , (d) f=open(“test\\test2\z.txt”), , rs, , (c) f=open(“.\\test2\z.txt”), , x.txt, , 48. If the following code is executed, what will be the output of the following code?, , y.txt, , try.py, , z.txt, , print(name[3:10]), , (a) mputerS, , 49. Give the output, , he, , name=”ComputerSciencewithPython”, , (b) puterSc, , (c) mputerScie, , (d) puterScien, , lt2.reverse(), print(lt2), , ot, , lt2=[[‘one’,’two’,’three’],[5,4,6]], , (b) [[5, 4, 6], [‘one’, ‘two’, ‘three’]], , (c) [[6,4,5] ,[‘three’, ‘two’, ‘one’]], , (d) Error message, , SECTION - C, , al, , Br, , (a) [[‘three’, ‘two’, ‘one’],[6,4,5]], , Case Study Based Questions., , G, , oy, , This section consists of 6 Questions (50-55). Attempt any 5 questions., Pooja wants to write a function Show_words() in python to read the content of a text file ‘NOTES.TXT’ and, display the entire content in capital letters. She has written some lines of program but facing some probems in some, statements. Help Pooja and fill the missing statement to complete the program., Example, if the file contains:, “This is a test file”, Then the function should display the output as:, THIS IS A TEST FILE, Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 161
Page 169 :
She has written coding:, def Show_words():, f=open(‘NOTES.TXT’,’__’), Lines = f.__________, for L in ______:, print(______), ______, __________, , 50. Write mode of opening the file in statement-1?, (b) re, , (a) a, , (c) w, , (d) r, , 51. Fill in the blank in statement-2 to read the data from the file., (b) read(), , (a) File.Read(), , (c) read.lines( ), , (b) Line, , (d) readlines( ), , Pr, ak, , 52. Fill in the blank in statement-3 to read data by for loop., (a) Lines, , 1, 2, 3, 4, 5, , as, ha, n, , #statement, #statement, #statement, #statement, #statement, , (c) lines, , (d) line, , 53. Fill in the blank in statement-4, which display the data in upper case., (b) upper(L), , (a) L.ucase(), , 54. Fill in the blank in statement-5 to close the file., (b) f.close(), , (a) close(f), , (c) L.upper(), , (d) L.toupper(), , (c) close(f), , (d) f_close(), , 55. .Fill in the blank in statement-5 to call the function Show_words()., (b) def Show_words(), , (c) Show_words(), , (d) f.Show_words(), , rs, , (a) call Show_words(), , he, , Answers (Model Test Paper – 4), 2. (b), 12. (a), , 3. (c), 13. (a), , 4. (d), 14. (c), , 5. (b), 15. (a), , 6. (b), 16. (d), , 7. (d), 17. (d), , 8. (a), 18. (d), , 9. (c), 19. (c), , 10. (c), 20. (a), , 21. (c), 31. (a), 41. (a), , 22. (c), 32. (a), 42. (a), , 23. (d), 33. (a), 43. (d), , 24. (d), 34. (a), 44. (b), , 25. (a), 35. (b), 45. (d), , 26. (a), 36. (b), 46. (d), , 27. (d), 37. (a), 47. (a), , 28. (a), 38. (a), 48. (b), , 29. (b), 39. (b), 49. (b), , 30. (b), 40. (c), 50. (d), , 51. (d), , 52. (a), , 53. (c), , 54. (b), , 55. (c), , G, , oy, , al, , Br, , ot, , 1. (b), 11. (b), , 162, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 170 :
MODEL TEST PAPER – 5, , (Based on the Latest CBSE Sample Paper), Time Allowed : 90 Minutes, , as, ha, n, , Maximum Marks : 35, , General Instructions :, 1. The question paper is divided into 3 Sections - A, B, and C., 2. Section A consists of 25 Questions (1-25). Attempt any 20 questions., 3. Section B consists of 24 Questions (26-49). Attempt any 20 questions., 4. Section C consists of 6 case study based Questions (50-55). Attempt any 5 questions., 5. All questions carry equal marks., , Pr, ak, , SECTION - A, , This section consists of 25 Questions (1 to 25). Attempt any 20 questions from this section. Choose the best, possible option., 1. Identify the incorrect variable name., (a) unit@price, (b) fee, , (c) userid, , 2. Consider a declaration L = ‘Raja123’, Which of the following represents the data type of L?, (a) list, (b) tuple, (c) float, , (d) avgmarks, , (d) string, , he, , rs, , 3. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90)., What will be the output of print(t[::-1])?, (a) no output, (b) error message, (c) (10, 20, 30, 40, 50, 60, 70, 80, 90), (d) (90, 80, 70, 60, 50, 40, 30, 20, 10), , ot, , 4. Which of the following options is correct?, (a) Opening file in r+ mode means opening a file for reading only., (b) When file is opened in r+ mode, the file pointer is placed at the beginning of the file., (c) r+ is the default mode., (d) all of the above, , al, , Br, , 5. Which of the following options can be used to read the two lines of a text file in the form of string from, Myfile.txt. Assuming the file having two lines only., (a) myfile = open(‘Myfile.txt’); myfile.read(), (b) myfile = open(‘Myfile.txt’,’r’); myfile.read(2), (c) myfile = open(‘Myfile.txt’); myfile.readline(2), (d) myfile = open(‘Myfile.txt’); myfile.readlines(), 6. _______________ function closes the file and frees the memory space acquired by that file., (a) close(), (b) close, (c) closed(), (d) closes(), , G, , oy, , 7. Which option is correct when file is opened in ‘a’ mode?, (a) Opens a file for appending., (b) The file pointer is at the end of the file if the file exists., (c) If the file does not exist, it creates a new file for writing., (d) all of the above, 8. The return type of the split() function is, (a) string, (b) integer, , (c) list, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , (d) tuple, 163
Page 171 :
9. The expression ‘5’+’5’ will return, (a) ‘55’, (b) ’10’, , (c) ’5’’5’, , (d) 10, , 10. Identify the valid arithmetic operator in Python from the following., (a) ?, (b) <, (c) //, , 12. Give the output, , f=open(‘c:\\abc.txt’), g=f.read(5), t=f.tell(), print(t), , (a) 5, , (b) 6, , (c) 4, , 13. Which statement is correct?, (a) import pickle as i , (c) import Pickle as P , , (d) load, , (d) 0, , (b) import pickles as p, (d) import Pickles as I, , 14. Which statement is not valid?, (a) f.seek(), (b) f.seek(0), , Pr, ak, , , , , , , as, ha, n, , 11. _______________ function is used to read from pickle file in Python., (a) read, (b) readdata, (c) pickread, , (d) and, , (c) f.seek(1), , (d) f.seek(2), , 15. The list of parameters used in the function definition is called, (a) actual parameter(s) , (b) formal parameter(s), (c) value parameter(s) , (d) type parameter(s), , 17. Give the output, , (d) def prt(1,2), , (c) 90, , (d) -30, , (c) .cs, , (d) .sv, , ot, , he, , def abc(x,y=60):, , if x>y:, , print(x+y), , else:, , print(x-y), a,b=20,30, abc(b,a), , (c) def prt(0), , rs, , 16. Which of the following function header is correct?, (a) def prt(), (b) def prt, , (a) 50, , (b) 80, , Br, , 18. The extension of CSV file is _______________, (a) .csv, (b) .cv, , (d) writemany(), , 20. Which of the following is a function/method of csv module in Python?, (a) read(), (b) write(), (c) readrow(), , (d) writerow(), , al, , 19. __________ method takes 2-dimensional data (multiple rows)., (a) writedata(), (b) writetwo(), (c) writerows(), , G, , oy, , 21. Which of the following options is not correct?, (a) if we try to open text file in r mode that does not exist, an error occurs., (b) if we try to open file in wb mode that does not exist, the file gets created., (c) if we try to open file in rb+ mode that does not exist, no error occurs., (d) if we try to open file in wb+ mode that does not exist, the file gets Created., , 22. Given a Tuple t= (10, 20, 30, 40, 50, 60, 70, 80, 90), What will be the output of print(t[3:2:1])?, (a) (30,20), (b) (20,30), (c) (30), 164, , (d) ( ), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 172 :
23. The return type of the len() function is, (a) string, (b) integer, , (c) list, , (d) tuple, , 24. Overwrites the file if the file exists when file is opened in, (a) r mode, (b) w mode, (c) a mode, (c) 2 parameters, , SECTION - B, This section consists of 24 Questions (26 to 49). Attempt any 20 questions., 26. Gives the output., tup1=((1,2,3,4,5),(“one”,”two”,”three”,”four”,”five”)), print(len(tup1)), , (b) 2, , (c) 5, , 27. Suppose content of ‘abc.txt’ is:, , (d) 3 parameters, , (d) 10, , Pr, ak, , (a) 1, , as, ha, n, , 25. item() method in dictionary takes _______________, (a) no parameter, (b) 1 parameter, , (d) all of these, , India is Great, I love my India, f=open(‘abc.txt’,’r’), data=f.readline(20), print(data), f.close(), , (b) India is Great, I love, , L.remove(3), print(L), , (a) [1,2,4,5], , (b) [1,2,3,5,3], , ot, , 28. L=[1,2,3,4,5,3], , he, , (a) India is Great, I lov, , rs, , What will be the output of the following code?, , (c) India is Great, , (d) India is Great, I love, my I, , (c) [1,2,4,5,3], , (d) [1,2,3,4,5], , 29. What will be the values of variables agg after execution of the following loops?, , Br, , a=9, agg=9, while(a>10):, agg+=a, a-=2, , al, , (a) agg=9, , (b) 14, , (c) 16, , (d) 18, , 30. What will be the value of A and B after execution of the following code:, , oy, , A = 100, for B in, range(10, 13):, A+=B, print(“A:”,A,”B:”,B) ;, , G, , (a) A: 133 B: 12, , (b) A: 133 B: 11, , (c) A: 121 B: 11, , (d) A: 121 B: 12, , 31. a=[10,20,30], print(a*3), , (a) [30,60,90], (c) [10,20,30,10,20,30,10,20,30], , (b) [10,20,30][10,20,30][10,20,30], (d) [180], , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , 165
Page 173 :
32. Aman wants to read pickled file ELECTION.DAT and displays every such Name whose Count is less than 10, but facing some problems to give the condition., The File contains the following fields :, , Choose the correct option which satisfied the condition., (a) E<10, (b) E[2]<10, (c) E[1]<10, , as, ha, n, , Name,Count, import pickle, def cLowCount():, , file=open(‘ELECTION.DAT’,’rb’), , ERec=pickle.load(file) #To read the object from file, , for E in ERec:, , if __________:, # statement 1, , print (E[0] ), , file.close(), , (d) E[0]<10, , Pr, ak, , 33. Which of the following options is incorrect?, (a) Reading and Writing both can be done when file is opened in r+ mode., (b) When file is opened in r+ mode the file pointer is placed at the beginning of the file., (c) Only Reading in binary file can be done when file is opened in rb+ mode., (d) When file is opened in rb+ mode the file pointer is placed at the beginning of the file., def abc(x,y=60):, return x+y, a=20, b=30, a=abc(a,b), print(a,b), , (b) 80,60, , he, , (a) 80,30, , rs, , 34. Give the output, , , , , , , , , (c) 50,30, , 35. Evaluate the following expression and identify the correct answer., x= 6 * 3 + 4**2 // 5 – 8, (a) 13, (b) 14, (c) 15, , (d) 50,60, , (d) 16, , ot, , 36 What will be the output of the following code?, , Br, , def my_func(var1, var2=200):, var1+=10, var2 = var1 - 50, return var1+var2, print(my_func(50),my_func(20,30)), , (a) 70,10, , (b) 10,10, , (c) 10,180, , (d) 70,180, , (c) 3 5, , (d) 3 8, , al, , 37. What will be the output of the following code?, , G, , oy, , a=3, def demo(x,y):, , global a,b, , a=a+x+y, , z=a+y, , b+=x, b=5, demo(a,b), print(a,b), , 166, , (a) 11 8, , (b) 11 5, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 174 :
38. What are the possible outcome(s) executed from the following code?, , as, ha, n, , import random, NAV, = [“LEFT”,”FRONT”,”RIGHT”,”BACK”], NUM, = random.randint(1,3), NAVG = “”, for C in range(NUM,1,-1):, , NAVG = NAVG+NAV[C], print (NAVG), , (a) BACKRIGHT , (c) BACK , , (b) BACKRIGHTFRONT, (d) LEFTFRONTRIGHT, , :, 5, :, 3, , L=[ 10,24,16,15], ChangeVal(L,4), for i in L :, , print(i, end=’#’), , (b) 2#8#16#1#, , 40. Suppose content of ‘Myfile.txt’ is, , (c) 2#8#16#5#, , (d) 2#8#16#3#, , rs, , (a) 2#8#4#1#, , Pr, ak, , 39. What is the output of the following code snippet?, def ChangeVal(M,N):, , for i in range(N):, , if M[i]%5 == 0, , M[i] //=, , if M[i]%3 == 0, , M[i] //=, , he, , You should always, close your files, in some, cases, due to buffering, changes, made to a file may not, show until you close the file, , ot, , What will be the output of the following code?, , (a) 3, , Br, , myfile = open(“Myfile.txt”), record = myfile.read().split(‘,’), print(len(record)), myfile.close(), , (b) 4, , (c) 5, , (d) 6, , 41. Find and write the output of the following python code:, , G, , oy, , al, , Msg1=’WeLcOME’, Msg2=’GUeSTs’, Msg3=’’, for I in range(0,len(Msg2)+1):, , if Msg1[I]>=’A’ and Msg1[I]<=’M’:, , Msg3=Msg3+Msg1[I], , elif Msg1[I]>=’N’ and Msg1[I]<=’Z’:, , Msg3=Msg3+Msg2[I], , else:, , Msg3=Msg3+’*’, print (Msg3), , (a) W*e*SME, , (b) G*L*TME, , (c) G*L*T*E, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , (d) W*L*TME, 167
Page 175 :
(c) PPW%RRllN%, , (d) PpW%RrllN%, , Pr, ak, , (a) PPW%RRLLN%, (b) PPWCRRllNC, 43. Suppose content of ‘Myfile.txt’ is, , as, ha, n, , 42. Find the output of the following program :, , def ChangeIt(Text,C):, , T=””, , for K in range(len(Text)):, , if Text[K]>=’F’ and Text[K]<=’L’:, , T=T+Text[K].lower();, , elif Text[K]==’E’ or Text[K]==’e’:, , T=T+C;, , elif K%2==0:, , T=T+Text[K].upper(), , else:, , T=T+T[K-1], , print(T), OldText=”pOwERALone”, ChangeIt(OldText,”%”), , Honesty is the best policy., Be Honest., What will be the output of the following code?, myfile = open(“Myfile.txt”), record = myfile.read(), x=record.count(“Honest”), print(x), myfile.close(), , ot, , he, , import random, VAL=[15,25,35,45,55,65,75,85];, From=random.randint(1,3), To =random.randint(From,4), for I in range(From,To+1):, , print (VAL[I],”*”,), , rs, , (a) 0, (b) 1, (c) 2, (d) 3, 44. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from, the following code?, , al, , Br, , (a) 35 * 45 * 55 * 65 * 75 * , (b) 35 * 45 * 55 *, (c) 15 * 25 * 35 * 45 * , (d) 35 * 45 * 55 * 65 *, 45. Which statement is correct to open the file using with statement?, (a) with open(‘abc.txt’, ‘w’) to f:, (b) open(‘abc.txt’, ‘w’) with f:, (c) f=with open(‘abc.txt’, ‘w’) , (d) with open(‘abc.txt’, ‘w’) as f:, 46. Divya has written a function countmy( )in Python to read the text file “DATA.TXT” and count the number, oftimes “my” occurs in the file. For example if the file “DATA.TXT” contains: “This is my website. I have, displayed my preferences in the CHOICE section.” The countmy( ) funnction should display the output as, , “my occurs 2 times”, , countmy():, f=open(“DATA.TXT”,”r”), k=f.read(), p=k.split(), _____________, #statement 1, print(“my occurs”,c,”times”), f.close(), , G, , oy, , def, , , , , , , , Select the appropriate statement to fill the statement 1., (a) c=k.count(“my”), (b) c=p.count[“my”], (c) p=k.count(“my”), 168, , (d) c=p.count(“my”), , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)
Page 176 :
47. A folder Test is created in root directory C:\. Two subfolders test1 ,test2 and one “x.txt”, is created in Test Folder. “y.txt” and “Try.py” are created in folder Test1 and “z.txt”, is created in Test2., , C:\, , Choose the correct option to write single line statement in “Try.py” to open the, “x.txt” file which is stored in folder Test using relative path., , as, ha, n, , (a) f=open(“x.txt”), , (b) f=open(“.\\x.txt”), , (c) f=open(“test\\x.txt”), , (d) f=open(“..\\x.txt”), , i = 1, sum1 = 0, while i<10:, sum1 =sum1+ i, i =i+2, , (a) 24, , (b) 25, , 49. What will be the output of the following code?, tup1 = (1,2,[1,2],3), tup1[2]=3.14, print(tup1), , (a) (1,2,[3.14],3), , (b) (1,2,3.14,3), , x.txt, , Test 1, , y.txt, , Test 2, , try.py, , z.txt, , Pr, ak, , 48. Write the value of sum1 after execution of the following WHILE loop :, , Test, , (c) 26, , (d) 27, , (c) (1,2,[1,2,3.14],3), , (d) Error Message, , rs, , SECTION - C, , Case Study Based Questions., , Br, , ot, , he, , This section consists of 6 Questions (50-55). Attempt any 5 questions., Arun, during Practical Examination of Computer Science, has been assigned an incomplete search() function to, search a record which is passed as parameter in a pickled file student.dat. The File student.dat is created by, his Teacher and the following information is known about the file., (a) File contains details of students in [roll_no,name,marks] format., (b) File contains details of 10 students (i.e. from roll_no 1 to 10) and separate list of each student is written in, the binary file using dump()., Arun has been assigned the task to complete the code and print details of roll number1., def search(r):, f = open(“student.dat”,____), ____:, while True:, rec = pickle.____, if(____):, ________, except:, pass, ____, , #Statement-1, #Statement-2, , oy, , al, , #Statement-3, #Statement-4, #Statement-5, #Statement-6, , G, , 50. In which mode Arun should open the file in Statement-1?, (a) r, , (b) r+, , (c) rb, , (d) wb, , 51. Identify the suitable code to be used at blank space in line marked as Statement2., (a) Try, , (b) while True, , (c) try, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I), , (d) pass, 169
Page 177 :
52. Identify the function (with argument), to be used at blank space in line marked as Statement-3., (a) load(), , (b) f.load(), , (c) load(f), , (d) f(load), , 53. What will be the suitable code for blank space in line marked as Statement-4., (b) rec[1]==’r’, , (c) rec[1]==r, , (d) rec[0]==r, , as, ha, n, , (a) rec(0)==r, , 54. What will be the suitable code for blank space in line marked as Statement-5 to show record?, (a) show(rec), , (b) print(rec), , (c) print.rec(), , (d) rec(print), , 55. Which statement Arun should use at blank space in line marked as Statement5 to close the file?, (a) file.close(), , (b) close(file), , (c) f.close(), , Answers (Model Test Paper – 5), 3. (d), 13. (a), , 4. (b), 14. (a), , 5. (a), 15. (b), , 21. (c), 31. (c), 41. (b), , 22. (d), 32. (c), 42. (c), , 23. (b), 33. (c), 43. (c), , 24. (b), 34. (c), 44. (b), , 25. (a), 35. (a), 45. (d), , 51. (c), , 52. (c), , 53. (d), , 54. (b), , 55. (c), , 6. (a), 16. (a), , 7. (d), 17. (a), , 26. (b), 36. (a), 46. (d), , 27. (c), 37. (a), 47. (d), , 8. (c), 18. (a), , 9. (a), 19. (c), , 10. (c), 20. (d), , 28. (c), 38. (a), 48. (b), , 29. (a), 39. (b), 49. (d), , 30. (a), 40. (b), 50. (c), , Pr, ak, , 2. (d), 12. (a), , G, , oy, , al, , Br, , ot, , he, , rs, , 1. (a), 11. (d), , (d) close(), , 170, , Score Plus Question Bank with CBSE Sample Paper and Model Test Papers in Computer Science-12 (Term I)