0% found this document useful (0 votes)
459 views56 pages

12th Computer Science Sura Guide 2023 24 EM (1)

Uploaded by

abishekstar7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
459 views56 pages

12th Computer Science Sura Guide 2023 24 EM (1)

Uploaded by

abishekstar7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

www.kalvinesan.

com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores

COMPUTER SCIENCE

m
e
12 Standard
th FreWorkbook
e
Practic with

co
anual
Lab M
Based on the Updated New Textbook

.
Salient Features

ks
 Answers for all Textual Questions.
 Exhaustive Additional MCQs, VSA and SA question with answers are given in each chapter.
oo
 All the objective type (1 Mark) questions are given with 4 options.
(i) Choosing the correct option
(ii) Matching
ab

(iii) Filling the blanks


(iv) Choosing the Correct \ Incorrect Statement.
(v) Picking the Odd one Out.
(vi) Assertion and Reason.
ur

 Model Question Papers 1 to 6 (PTA) : Questions are incorporated in the appropriate sections.
 Govt. Model Question Paper - 2019 (Govt. MQP-2019), Quarterly Exam - 2019 (QY-2019),
Half Yearly Exam - 2019 (HY-2019), Public Exam March - 2020 & May 2022 (Mar-2020 &
.s

May-2022), Supplementary Exam September - 2020, August 2021 & July-2022 (Sep-2020,
Aug-2021 & July-'22) and First & Second Revision Test - 2022 (FRT-'22 & SRT-'22) questions
are incorporated in the appropriate sections.
w

 Instant Supplementary Exam July 2022 Question Paper is given with answers.
w
w

SURA PUBLICATIONS
Chennai

For Orders Contact


80562 94222 / 81242 01000 / 81243 01000
96001 75757 / 78718 02000 / 98409 26027

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores

2023-24 Edition
All rights reserved © SURA Publications.
No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or
by any means, digitally, electronically, mechanically, photocopying, recorded or otherwise, without the
written permission of the publishers. Strict action will be taken.

m
ISBN : 978-93-5330-523-9
Code No : SG91

co
Author :
Mr. Shanmugasundaram

.
(Post Graduate Teacher, Chennai)

ks
Edited by :
Mrs. Malathy Krishnamoorthy M.Sc.,
Erode
oo
Reviewed by :
Mr. Balaji M.Sc., M.Phil.
Chennai
ab

Also available for XI & XII Standard


Guides : ✤ Sura’s Bio-Zoology & Zoology (EM/TM)
ur

(Short Version & Long Version)


✤ RuhÉ‹ jÄœ ciuüš
✤ Sura’s Smart English ✤ Sura’s Computer Science (EM/TM)
✤ Sura’s Mathematics (EM/TM) ✤ Sura’s Computer Applications (EM/TM)
.s

✤ Sura’s Physics (EM/TM) ✤ Sura’s Commerce (EM/TM)


✤ Sura’s Chemistry (EM/TM) ✤ Sura’s Economics (EM/TM)
w

✤ Sura’s Bio-Botany & Botany (EM/TM) ✤ Sura’s Accountancy (EM/TM)


(Short Version & Long Version) ✤ Sura’s Business Maths (EM)
w

Head Office: For Orders Contact


Sura Publications 80562 94222
w

1620, ‘J’ Block, 16th Main Road, 81242 01000


Anna Nagar, Chennai - 600 040.
81243 01000
Phones : 044 - 4862 9977, 044 - 4862 7755.
96001 75757
15/11/2022

e-mail : [email protected]
website : www.surabooks.com
78718 02000
98409 26027
ii

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores

TO ORDER WITH US
SCHOOLS and TEACHERS:
We are grateful for your support and patronage to ‘SURA PUBLICATIONS’
Kindly prepare your order in your School letterhead and send it to us.
For Orders contact: 81242 01000 / 81243 01000
DIRECT DEPOSIT

m
A/c Name : Sura Publications A/c Name : Sura Publications
Our A/c No. : 36550290536 Our A/c No. : 21000210001240
Bank Name : STATE BANK OF INDIA Bank Name : UCO BANK

co
Bank Branch : Padi Bank Branch : Anna Nagar West
IFSC : SBIN0005083 IFSC : UCBA0002100

A/c Name : Sura Publications A/c Name : Sura Publications


Our A/c No. : 6502699356 Our A/c No. : 1154135000017684

.
Bank Name : INDIAN BANK Bank Name : KVB BANK

ks
Bank Branch : Asiad Colony Bank Branch : Anna Nagar
IFSC : IDIB000A098 IFSC : KVBL0001154

A/c Name : Sura Publications A/c Name : Sura Publications


Our A/c No. :
oo
13240200032412 Our A/c No. : 50200031530945
Bank Name : FEDERAL BANK Bank Name : HDFC BANK
Bank Branch : Anna Nagar Bank Branch : Cenotaph Road, Teynampet
IFSC : FDRL0001324 IFSC : HDFC0001216
ab

A/c Name : Sura Publications


Our A/c No. : 446205000010
Bank Name : ICICI BANK
Bank Branch : Anna Nagar
ur

IFSC : ICIC0004462
After Deposit, please send challan and order to our address.
email to : [email protected] / Whatsapp : 81242 01000.
.s

For Google Pay : For PhonePe :


98409 26027 98409 26027
w

DEMAND DRAFT / CHEQUE


 lease send Demand Draft / cheque in favour of ‘SURA PUBLICATIONS’
P
payable at Chennai. The Demand Draft / cheque should be sent with your order
w

in School letterhead.
STUDENTS :
Order via Money Order (M/O) to
w

Sura Publications
1620, ‘J’ Block, 16th Main Road, Anna Nagar, Chennai - 600 040.
Phones : 044-4862 9977, 044-4862 7755.
Mobile : 96001 75757 / 81242 01000 / 81243 01000.
email : [email protected] Website : www.surabooks.com

iv

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores

Contents

Chapter Page
Unit
No
Title No
Month

m
1. Function 1-8 June
UNIT- I
2. Data Abstraction 9-17 June

co
Problem
Solving 3. Scoping 18-27 June
Techniques
4. Algorithmic Strategies 28-43 June

.
ks
5. Python -Variables and Operators 44-60 July

UNIT- II 6. Control Structures 61-77 July

Core Python 7.
oo
Python functions 78-98 July

8. Strings and String manipulation 99-114 Aug

UNIT-III 9. Lists, Tuples, Sets and Dictionary 115-138 Aug


ab

Modularity and
OOPS 10. Python Classes and objects 139-151 Aug

UNIT-IV 11. Database Concepts 152-169 Oct


ur

Database
12. Structured Query Language (SQL) 170-191 Oct
concepts and
MySql 13. Python and CSV files 192-209 Oct
.s

UNIT-V 14. Importing C++ programs in Python. 210-223 Oct


w

Integrating 15. Data manipulation through SQL 224-237 Nov


Python with
MySql and Data visualization using pyplot: line
16. Nov
w

238-250
C++ chart, pie chart and bar chart

Instant Supplementary Exam July 2022 Question Paper with answers 251-258
w

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores

UNIT-I
 
PROBLEM SOLVING TECHNIQUES

1
Chapter
FUNCTION

m
co
CHAPTER SNAPSHOT
1.1 Introduction
1.2 Function with respect to Programming language

.
1.2.1 Function Specification

ks
1.2.2 Parameters (and arguments)
1.3 Interface Vs Implementation
1.3.1 Characteristics of interface
1.4 Pure functions
oo
1.4.1 Impure functions
1.4.2 Side-effects (Impure functions)
1.4.3 Chameleons of Chromeland problem using function
ab

Evaluation 4. The variables in a function definition are called


as  [PTA-2; QY-2019]
Part - I (a) Subroutines (b) Function
ur

(c) Definition (d) Parameters


Choose the best answer  (1 mark)  [Ans. (d) Parameters]
1. The small sections of code that are used to
perform a particular task is called 5. The values which are passed to a function
.s

 [Aug-2021; FRT-'22] definition are called [HY-2019; FRT-'22]


(a) Subroutines (b) Files (a) Arguments (b) Subroutines
(c) Pseudo code (d) Modules (c) Function (d) Definition
w

 [Ans. (a) Arguments]


 [Ans. (a) Subroutines]
2. Which of the following is a unit of code that is 6. Which of the following are mandatory to write
often defined within a greater code structure? the type annotations in the function definition?
w

 [July-'22]  [PTA-4; FRT-'22]


(a) Subroutines (b) Function (a) Curly braces (b) Parentheses
w

(c) Files (d) Modules (c) Square brackets (d) Indentations


 [Ans. (b) Function]  [Ans. (b) Parentheses]
3. Which of the following is a distinct syntactic 7. Which of the following defines what an object
block? [PTA-6; FRT & May-'22] can do?
(a) Subroutines (b) Function (a) Operating System (b) Compiler
(c) Definition (d) Modules (c) Interface (d) Interpreter
 [Ans. (c) Definition]  [Ans. (c) Interface]

[1]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit I - Chapter 1

8.
Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


Which of the following carries out the
instructions defined in the interface?
5.
 
Which of the following is a normal function
definition and which is recursive function
(a) Operating System (b) Compiler definition.
(c) Implementation (d) Interpreter i) let sum x y :
 [Ans. (c) Implementation] return x + y
ii) let disp :
9. The functions which will give exact result print 'welcome'
when same arguments are passed are called
iii) let rec sum num :

m
 [PTA-3; Mar.-2020] if (num!=0) then return num + sum
(a) Impure functions (b) Partial Functions (num-1)
(c) Dynamic Functions (d) Pure functions else

co
 [Ans. (d) Pure functions] return num
10. The functions which cause side effects to the Ans. (i) Recursive function
arguments passed are called (ii) Normal function
(a) Impure function (b) Partial Functions (iii) Recursive function

.
(c) Dynamic Functions (d) Pure functions
Part - III

ks
 [Ans. (a) Impure function]
Part - II Answer the following questions
Answer the following questions  (3 marks)
 (2 marks) 1. Mention the characteristics of Interface.
oo
1. What is a subroutine? [PTA-1; HY-2019]  [Sep-2020]
Ans. (i) Subroutines are the basic building blocks of Ans. (i) The class template specifies the interfaces to
computer programs. Subroutines are small enable an object to be created and operated
sections of code that are used to perform a properly.
ab

particular task that can be used repeatedly. (ii) An object's attributes and behaviour is
(ii) In Programming languages these controlled by sending functions to the object.
subroutines are called as Functions. 2. Why strlen is called pure function?
2. Define Function with respect to Programming  [Govt. MQP-2019]
ur

language. [Aug-2021; FRT-'22] Ans. (i) strlen is a pure function because the function
Ans. A function is a unit of code that is often defined takes one variable as a parameter, and accesses
within a greater code structure. Specifically, a it to find its length.
function contains a set of code that works on (ii) This function reads external memory but does
.s

many kinds of inputs, like variants, expressions not change it, and the value returned derives
and produces a concrete output. from the external memory accessed.
3. What is the side effect of impure function. Give
w

3. Write the inference you get from X:=(78).


Ans. X:= (78) has an expression in it but (78) is not example. [PTA-5]
itself an expression. Rather, it is a function Ans. Impure Function has the following side effects
w

definition. Definitions bind values to names, in (i) Function impure (has side effect) is that it
this case the value 78 being bound to the name doesn't take any arguments and it doesn't
‘X’. return any value.
w

4. Differentiate interface and implementation. (ii) Function depends on variables or functions


outside of its definition block.
Ans. The difference between interface and
implementation is (iii) It never assure you that the function will
behave the same every time it's called.
Interface Implementation
For example :
Interface just defines Implementation let y := 0
what an object carries out the (int) inc (int) x
can do, but won't instructions defined in y: = y + x;
actually do it the interface return (y)
2
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


(iv) Here, the result of inc() will change every
Part - IV
time if the value of 'y' get changed inside
the function definition. Answer the following questions

Function
(v) Hence, the side effect of inc () function  (5 marks)
is changing the data of the external 1. What are called Parameters and write a note
variable 'y'. on [PTA-2; May-'22]

m
4. Differentiate pure and impure function. (i) Parameter without Type [FRT-'22]
(ii) Parameter with Type
Ans.  [PTA-3, 6; Mar.-2020]
Ans. Parameters (and arguments) : Parameters
S. No. Pure Impure

co
are the variables in a function definition and
(i) The return value of The return value arguments are the values which are passed to a
the pure functions of the impure function definition.
solely depends functions does (i) Parameter without Type : Let us see an
on its arguments not solely depend example of a function, definition :

.
passed. on its arguments (requires: b>=0 )

ks
passed. (returns: a to the power of b)
(ii) If you call the pure If you call the let rec pow a b:=
functions with impure functions if b=0 then 1
else a * pow a (b –1)
the same set of
oo
with the same set
arguments, you will of arguments, ■  In the above function definition variable
‘b’ is the parameter and the value which is
always get the same you might get the
passed to the variable ‘b’ is the argument.
return values. different return The precondition (requires) and
ab

values. postcondition (returns) of the function is


(iii) They do not have They have given.
any side effects. side effects. ■  Note we have not mentioned any types:
For example: For example: (data types). Some language compiler
ur

strlen(), sqrt() random(), Date(). solves this type (data type) inference
(iv) They do not modify They may modify problem algorithmically, but some require
the arguments the arguments the type to be mentioned.
■  In the above function definition if
.s

which are passed to which are passed


them to them expression can return 1 in the then branch,
shows that as per the typing rule the entire
5. What happens if you modify a variable outside if expression has type int.
w

the function? Give an example.


■  Since the if expression is of type ‘int’, the
Ans. One of the most popular groups of side effects is function's return type also be ‘int’. ‘b’ is
modifying the variable outside of function.
w

compared to 0 with the equality operator,


For example : so ‘b’ is also a type of ‘int’. Since ‘a’ is
let y: = 0 multiplied with another expression using
the * operator, ‘a’ must be an int.
w

(int) inc (int) x


y: = y + x; (ii) Parameter with Type : Now let us write
return (y) the same function definition with types
for some reason:
 Here, the result of inc () will change every
(requires: b> 0 )
time if the value of 'y' get changed inside the
(returns: a to the power of b )
function definition. Hence, the side effect of inc let rec pow (a: int) (b: int) : int :=
() function is changing the data of the external if b=0 then 1
variable 'y'. else a * pow b (a-1)
3
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit I - Chapter 1

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


■ When we write the type annotations for
‘a’ and ‘b’ the parentheses are mandatory.
 
(iv) The above function square is a pure function
because it will not give different results for
Generally we can leave out these same input.
annotations, because it's simpler to let the (v) There are various theoretical advantages of
compiler infer them. having pure functions. One advantage is
■ Th
 ere are times we may want to explicitly that if a function is pure, then if it is called
several times with the same arguments,
write down types. This is useful on
the compiler only needs to actually call the

m
times when you get a type error from function once. Lt’s see an example
the compiler that doesn't make sense.
let i: = 0;
Explicitly annotating the types can help
if i <strlen (s) then

co
with debugging such an error message.
-- Do something which doesn't affect s
2. Identify in the following program [PTA-5] ++i
let rec gcd a b := (vi) If it is compiled, strlen (s) is called each
if b <> 0 then gcd b (a mod b) else return a time and strlen needs to iterate over the

.
whole of ‘s’. If the compiler is smart enough

ks
i) Name of the function to work out that strlen is a pure function
ii) Identify the statement which tells it is a and that ‘s’ is not updated in the loop, then
recursive function it can remove the redundant extra calls to
iii) Name of the argument variable strlen and make the loop to execute only
iv) 
oo
Statement which invoke the function one time.
recursively (vii) From these what we can understand, strlen
v) Statement which terminates the recursion is a pure function because the function
takes one variable as a parameter, and
Ans. (i) gcd
accesses it to find its length. This function
ab

(ii) let rec gcd reads external memory but does not
(iii) a, b change it, and the value returned derives
(iv) gcd b (a mod b) from the external memory accessed.
(v) return a Impure functions :
ur

(i) The variables used inside the function may


3. Explain with example Pure and impure cause side effects though the functions
functions. which are not passed with any arguments.
Ans. Pure functions : In such cases the function is called impure
.s

Pure functions are functions which will


(i) function.
give exact result when the same arguments (ii) When a function depends on variables or
are passed. functions outside of its definition block,
w

(ii) For example the mathematical function sin you can never be sure that the function
(0) always results 0. This means that every will behave the same every time it’s called.
time you call the function with the same For example the mathematical function
w

arguments, you will always get the same random() will give different outputs for the
result. same function call.
let randomnumber:=
(iii) A function can be a pure function provided
w

it should not have any external variable a := random()


which will alter the behaviour of that if a > 10 then
variable. return: a
Let us see an example else
let square x return: 10
(iii) Here the function Random is impure as it
return: x * x
is not sure what will be the result when we
call the function.

4
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


4. Explain with an example interface and (iv) The person who drives the car doesn't care
implementation. about the internal working. To increase
Ans. Interface :
the speed of the car he just presses the

Function
accelerator to get the desired behaviour.
An interface is a set of action that an object
(i) Here the accelerator is the interface
can do. For example when you press a light between the driver (the calling / invoking
switch, the light goes on, you may not have object) and the engine (the called object).
cared how it splashed the light. In Object (v) In this case, the function call would be

m
Oriented Programming language, an Speed (70): This is the interface. Internally,
Interface is a description of all functions the engine of the car is doing all the things
that a class must have in order to be a new It's where fuel, air, pressure, and electricity
interface.

co
come together to create the power to move
(ii) In our example, anything that "ACTS the vehicle.
LIKE" a light, should have function (vi) All of these actions are separated from the
definitions like turn_on () and a turn_off driver, who just wants to go faster. Thus we
(). The purpose of interfaces is to allow the separate interface from implementation.

.
computer to enforce the properties of the
Hands on Practice

ks
class of TYPE T (whatever the interface is)
must have functions called X, Y, Z, etc.
(iii) A class declaration combines the
1. Write algorithmic function definition to find
external interface (its local state) with an the minimum among 3 numbers.
Ans. let min 3 x y z :=
oo
implementation of that interface (the code
that carries out the behaviour). An object if x < y then
is an instance created from the class. The if x < z then x else z
interface defines an object’s visibility to the else
outside world. if y < z then y else z
ab

Implementation :
(i) Implementation carries out the instructions 2. Write algorithmic recursive function definition
defined in the interface. to find the sum of n natural numbers.
(ii) How the object is processed and executed is Ans. let rec sum num:
the implementation. if (num!=0) then return num+sum num-1)
ur

(iii) A class declaration combines the else


external interface (its local state) with an return num
implementation of that interface (the code
Questions and Answers
.s

that carries out the behaviour). PTA


 For example, let's take the example of
increasing a car’s speed. 1 MARK
w

1. A function definition which call itself : [PTA-1]


ENGINE (a) Pure function (b) Impure function
(c) Normal function
w

(d) Recursive function


 [Ans. (d) Recursive function]
getSpeed
3 MARKS
w

No 1. Write a function that finds the minimum of its


required Pull Fuel three arguments. [PTA-4; QY-2019]
speed
Ans. let min 3 x y z :=
Yes if x < y then
if x < z then x else z
Return
else
if y < z then y else z

5
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

 
DATA ABSTRACTION
2
Chapter

m
co
CHAPTER SNAPSHOT
2.1 Data Abstraction – Introduction

.
2.2 Abstract Data Types

ks
2.3 Constructors and Selectors
2.4 Representation of Abstract datatype using Rational numbers
2.5 Lists, Tuples
2.5.1 List
oo
2.5.2 Tuple
2.6 Data Abstraction in Structure
ab

Evaluation 4. A sequence of immutable objects is called


 [Mar.-2020]
Part - I (a) Built in (b) List
ur

(c) Tuple (d) Derived data


Choose the best answer  (1 mark)  [Ans. (c) Tuple]
1. Which of the following functions that build the 5. The data type whose representation is known
abstract data type ? [Sep-2020; Aug-2021; July-'22]
.s

are called [PTA-2; QY-2019]


(a) Constructors (b) Destructors (a) Built in datatype
(c) Recursive (d) Nested (b) Derived datatype
[Ans. (a) Constructors]
w

 (c) Concrete datatype


2. Which of the following functions that retrieve (d) Abstract datatype 
information from the data type?  [Ans. (c) Concrete datatype ]
w

 [FRT & May-'22]


6. The data type whose representation is unknown
(a) Constructors (b) Selectors are called
(c) Recursive (d) Nested
w

(a) Built in datatype (b) Derived datatype


 [Ans. (b) Selectors] (c) Concrete datatype (d) Abstract datatype 
3. The data structure which is a mutable ordered  [Ans. (d) Abstract datatype]
sequence of elements is called
(a) Built in (b) List 7. Which of the following is a compound structure?
(c) Tuple (d) Derived data (a) Pair (b) Triplet
 [Ans. (b) List] (c) Single (d) Quadrat
 [Ans. (a) Pair]
[9]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit I - Chapter 2

8.
Sura’s

considered as
Available at All Leading Bookstores

➠ XII Std - Computer Science


Bundling two values together into one can be
[Govt. MQP - 2019; PTA-4]
4.
 
What is a List? Give an example.
Ans. (i)
[QY - 2019]
List is constructed by placing expressions
(a) Pair (b) Triplet within square brackets separated by
(c) Single (d) Quadrat commas.
 [Ans. (a) Pair] (ii) Such an expression is called a list literal.
List can store multiple values. Each value
9. Which of the following allow to name the can be of any type and can even be another

m
various parts of a multi-item object? [PTA-6] list.
(a) Tuples (b) Lists Example : lst := [10, 20]
(c) Classes (d) Quadrats x, y := lst

co
 [Ans. (c) Classes] 5. What is a Tuple? Give an example.
10. Which of the following is constructed by Ans. (i) A tuple is a comma-separated sequence of
placing expressions within square brackets? values surrounded with parentheses. Tuple
(a) Tuples (b) Lists is similar to a list.

.
(c) Classes (d) Quadrats (ii) The difference between the two is that you

ks
 [Ans. (b) Lists] cannot change the elements of a tuple once
it is assigned whereas in a list, elements can
Part - II be changed.
Answer the following questions (iii) Example : colour= ('red', 'blue', 'Green')
1. What is abstract data type? (2 marks)
oo Part - III
 [Aug-2021; FRT & May-'22]
Answer the following questions
Ans. (i) Abstract Data type (ADT) is a type (or
class) for objects whose behavior is defined  (3 marks)
ab

by a set of value and a set of operations.


1. Differentiate Concrete datatype and Abstract
(ii) The definition of ADT only mentions what datatype.
operations are to be performed but not how Ans.
these operations will be implemented.
S. Concrete
ur

2. Differentiate constructors and selectors. Abstract datetype


No. datatype
Ans.  [PTA-2, 3; QY-2019; July-'22] (i) Concrete Abstract Datatypes
S. datatypes or (ADT's) offer
Constructors Selectors
.s

No. structures a high level


(i) Constructors are Selectors are (CDT's) are direct view (and use)
functions that functions implementations of a concept
of a relatively independent of its
w

build the abstract that retrieve


data type. information from simple concept. implementation.
the data type. (ii) A concrete data Abstract data type
w

(ii) Constructors Selectors extract type is a data the representation


create an object, individual pieces of type whose of a data type is
bundling together information from representation is unknown.
different pieces of the object known.
w

information.
2. Which strategy is used for program designing?
3. What is a Pair? Give an example.  [Mar.-2020] Define that Strategy. [Govt. MQP-2019]
Ans. (i) Any way of bundling two values together Ans. A powerful strategy for designing programs:
into one can be considered as a Pair. Lists 'wishful thinking'. Wishful Thinking is the
are a common method to do so. Therefore formation of beliefs and making decisions
List can be called as Pairs. according to what might be pleasing to imagine
(ii) Example : lst = [(0,10), (1,20)] instead of by appealing to reality.

10
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


3. Identify Which of the following are Ans. (a) List
constructors and selectors? [PTA-5; FRT-22] (b) Tuple

Data Abstraction
(a) N1=number() (c) Class
(b) accetnum(n1) (d) Tuple
(c) displaynum(n1)
(e) List
(d) eval(a/b)
(f) Class
(e) x,y= makeslope (m), makeslope(n)
Part - IV

m
(f) display()
Answer the following questions
Ans. (a) Constructors  (5 marks)

co
(b) Selectors
1. How will you facilitate data abstraction.
(c) Selectors
Explain it with suitable example.
(d) Selectors
 [PTA-2, 4; FRT-'22]
(e) Constructors
(f) Ans. Data abstraction is supported by defining an

.
Selectors
abstract data type (ADT), which is a collection

ks
4. What are the different ways to access the of constructors and selectors. To facilitate data
elements of a list. Give example. abstraction, you will need to create two types of
Ans. (i) The elements of a list can be accessed in functions: Constructors and Selectors
two ways. The first way is via our familiar Constructors :
oo
method of multiple assignment, which (i) Constructors are functions that build the
unpacks a list into its elements and binds abstract data type.
each element to a different name.
(ii) Constructors create an object, bundling
lst := [10, 20] together different pieces of information.
ab

x, y := lst (iii) For example, say you have an abstract data


(ii) In the above example x will become10 and type called city.
y will become 20. (iv) This city object will hold the city's name,
and its latitude and longitude.
(iii) A second method for accessing the
ur

elements in a list is by the element selection (v) To create a city object, you'd use a function
operator, also expressed using square like city = makecity (name, lat, lon).
brackets. Unlike a list literal, a square- (vi) Here makecity (name, lat, lon) is the
brackets expression directly following
.s

constructor which creates the object city.


another expression does not evaluate to a
list value, but instead selects an element (name, lat, lon) value passed as parameter
from the value of the preceding expression.
w

lst[0]
10 make city ( )
lst[1]
w

20
5. Identify Which of the following are List, Tuple city
and class ?
w

lat lon
(a) arr [1, 2, 34]
(b) arr (1, 2, 34) Constructor

(c) student [rno, name, mark] Selectors :


(d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’) (i) Selectors are functions that retrieve
information from the data type.
(e) x= [2, 5, 6.5, [5, 6], 8.2]
(ii) Selectors extract individual pieces of
(f) employee [eno, ename, esal, eaddress] information from the object.

11
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit I - Chapter 2

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


(iii) To extract the information of a city object,
you would used functions like
 
Pair :
Any way of bundling two values together
getname(city) into one can be considered as a pair. Lists
getlat(city) are a common method to do so. Therefore
getlon(city) List can be called as Pairs.
These are the selectors because these
functions extract the information of the 3. How will you access the multi-item? Explain
city object. with example.

m
city value passed as parameter city value passed as parameter city value passed as parameter Ans. (i) The structure construct (In OOP languages
it's called class construct) is used to
getname ( ) getlat ( ) getlon ( ) represent multi-part objects where each

co
part is named (given a name). Consider the
following pseudo code:
2. What is a List? Why List can be called as Pairs. class Person:
Explain with suitable example. [PTA-6] creation( )

.
Ans. List : firstName := " "

ks
(i) List is constructed by placing expressions
lastName := " "
within square brackets separated by
commas. Such an expression is called a list id := " "
literal. List can store multiple values. Each email := " "
value can be of any type and can even be The new data type Person is pictorially
another list.
oo represented as
Example for List is [10, 20].
Person class name (multi part data representation)
(ii) The elements of a list can be accessed in
two ways. The first way is via our familiar
ab

function belonging to the new datatype


method of multiple assignment, which creation ( )

}
unpacks a list into its elements and binds
each element to a different name.
first Name
lst := [10, 20]
x, y := lst
ur

last Name
datatype
(iii) In the above example x will become10 and id
y will become 20. A second method for
accessing the elements in a list is by the email
.s

element selection operator, also expressed


using square brackets. Let main() contains
(iv) Unlike a list literal, a square-brackets p1:=Person() statement creates
the object
w

expression directly following another


expression does not evaluate to a list value, firstName := "Padmashri" setting a field called
but instead selects an element from the first Name with
value of the preceding expression. value Padmashri
w

lst[0] lastName :="Baskar" setting a field called


10 lastName with value
lst[1] Baskar
w

20 id :="994–222–1234" setting a field called


id value 994–222–
(v) In both the example mentioned above 1234
mathematically we can represent list similar
to a set. email="[email protected]" setting a filed called
email with value
lst[(0, 10), (1, 20)] - where compsci@gmail.
(o, 10) (1, 20) com
Index position Value Index position Value - - output of firstName : Padmashri

12
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

   
SCOPING
3
Chapter

m
CHAPTER SNAPSHOT
3.1 Introduction 3.5 Module

co
3.2 Variable Scope 3.5.1. Characteristics of Modules
3.3 LEGB rule 3.5.2. The benefits of using modular
3.4 Types of Variable Scope programming include
3.4.1. Local Scope 3.5.3. Access Control

.
3.4.2. Global Scope

ks
3.4.3. Enclosed Scope
3.4.4. Built-in-Scope

Evaluation 5. Which scope refers to variables defined in


oo current function? [FRT & July-'22]
Part - I (a) Local Scope (b) Global scope
(c) Module scope (d) Function Scope
Choose the best answer  (1 mark)  [Ans. (a) Local Scope]
ab

1. Which of the following refers to the visibility of


variables in one part of a program to another 6. The process of subdividing a computer
part of the same program. [FRT-'22]
program into separate sub-programs is called
(a) Scope (b) Memory (a) Procedural Programming
(b) Modular programming
ur

(c) Address (d) Accessibility


[Ans. (a) Scope] (c) Event Driven Programming
(d) Object oriented Programming
2. The process of binding a variable name with an
[Ans. (b) Modular programming]
.s

object is called [Sep-2020; Aug-2021; FRT-'22]


(a) Scope (b) Mapping 7. Which of the following security technique
(c) late binding (d) early binding that regulates who can use resources in a
w

[Ans. (b) Mapping] computing environment?


3. Which of the following is used in programming (a) Password (b) Authentication
languages to map the variable and object? (c) Access control (d) Certification
w

 [PTA-2; HY-2019] [Ans. (c) Access control]


(a) :: (b) := 8. Which of the following members of a class can
(c) = (d) == be handled only from within the class?
w

[Ans. (c) =]  [Mar.-2020]


4.  ontainers for mapping names of variables to
C (a) Public members
objects is called [QY-2019; May-'22] (b) Protected members
(a) Scope (b) Mapping (c) Secured members
(c) Binding (d) Namespaces (d) Private members
[Ans. (d) Namespaces] [Ans. (d) Private members]
[18]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


9. Which members are accessible from outside 5. How Python represents the private and
the class? protected Access specifiers?
(a) Public members Ans. Python prescribes a convention of prefixing

Scoping
(b) Protected members the name of the variable/method with single or
(c) Secured members (d) Private members double underscore to emulate the behaviour of
[Ans. (a) Public members] protected and private access specifiers.
Example: self_n2 = n2

m
10. The members that are accessible from within
the class and are also available to its sub-classes Part - III
is called [PTA-6] Answer the following questions
 (3 marks)

co
(a) Public members
1. Define Local scope with an example.
(b) Protected members
 [Aug-2021]
(c) Secured members (d) Private members
Ans. (i) Local scope refers to variables defined in
[Ans. (b) Protected members]
current function. Always, a function will

.
Part - II first look up for a variable name in its local

ks
Answer the following questions scope.
(ii) Only if it does not find it there, the outer
 (2 marks) scopes are checked.
1. What is a scope? oo (iii) Look at this example :
Ans. Scope refers to the visibility of variables,
1. Disp(): Entire program Output
parameters and functions in one part of a
2. a:=7 of the
program to another part of the same program.
3. print a Disp( ): Program
a:=7
2. Why scope should be used for variable. State 4. Disp() print a 7
ab

the reason. [FRT-'22] Disp ( )

Ans. The scope should be used for variables because;


it limits a variables scope to a single definition. (iv) On execution of the above code the variable
That is the variables are visible only to that part a displays the value 7, because it is defined
ur

of the code. Essentially, variables are addresses and available in the local scope.
(references, or pointers), to an object in memory. 2. Define Global scope with an example.
When you assign a variable with := to an  [PTA-6; FRT-'22]
.s

instance (object), you're binding (or mapping) Ans. (i) A variable which is declared outside of all
the variable to that instance. Multiple variable the functions in a program is known as
can be mapped to the same instance. Global variable.
(ii) This means, global variable can be accessed
w

3. What is Mapping? [PTA-5; May-'22] inside or outside of all the functions in a


Ans. The process of binding a variable name with an program. Consider the following example
object is called mapping.= (equal to sign) is used
w

1. a:=10 Entire program Output


in programming languages to map the variable 2. Disp(): of the
a:=10
and object. 3. a:=7 Disp( ): Program
w

a:=7
4. What do you mean by Namespaces? 4. print a print a 7
 [Govt. MQP-2019; PTA-4; Mar.-2020; FRT & 5. Disp() Disp ( ): 10
print a
July-'22] 6. print a
Ans. Namespaces are containers for mapping names (iii) On execution of the above code the variable
of variables to objects. a which is defined inside the function
Example : a : = 5 displays the value 7 for the function call
Disp() and then it displays 10, because a is
Here the variable 'a' is mapped to the value '5'.
defined in global scope.
19
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit I - Chapter 3

3.

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


Define Enclosed scope with an example.
[PTA-3; FRT-'22]
 
Ans. Output :
Red Blue Green
Ans. (i) All programming languages permit Red Blue
functions to be nested. A function (method) Red
within another function is called nested Scope of Variables :
function.
Variables Scope
(ii) A variable which is declared inside a

m
function which contains another function Color:=Red Global
definition with in it, the inner function
b:=Blue Enclosed
can also access the variable of the outer

co
function. This scope is called enclosed G:=Green Local
scope.
Part - IV
(iii) When a compiler or interpreter search for a
variable in a program, it first search Local, Answer the following questions

.
and then search Enclosing scopes. Consider  (5 marks)

ks
the following example
1. Disp(): Entire program Output 1. Explain the types of scopes for variable or
2. a:=10 Disp( ):
of the LEGB rule with example.
3. Disp1(): a:=10 Program  [PTA-1; Sep-2020; May-'22]
4. print a
Disp 1( ):
oo 10
print a Ans. Types of Variable Scope :
5. Disp1() Disp 1( ) 10 There are 4 types of Variable Scope, let's discuss
print a
6. print a Disp( )
them one by one:
7. Disp() Local Scope : [FRT-'22]
ab

4. Why access control is required? (i) Local scope refers to variables defined in
 [PTA-1; HY-2019] current function. Always, a function will
first look up for a variable name in its local
Ans. (i) Access control is a security technique that scope. Only if it does not find it there, the
regulates who or what can view or use
ur

outer scopes are checked.


resources in a computing environment.
Look at this example
(ii) It is a fundamental concept in security that
minimizes risk to the object. 1. Disp(): Entire program Output
.s

(iii) In other words access control is a selective 2. a:=7 of the


restriction of access to data. 3. print a Disp( ): Program
a:=7
(iv) In oops Access control is implemented 4. Disp() print a 7
w

through access modifiers. Disp ( )

5. Identify the scope of the variables in the


following pseudo code and write its output
w

(ii) On execution of the above code the variable


color:= 'Red'
a displays the value 7, because it is defined
mycolor():
and available in the local scope.
b:='Blue'
w

myfavcolor(): Global Scope:


g:='Green' (i) A variable which is declared outside of all
printcolor, b, g the functions in a program is known as
myfavcolor() global variable.
printcolor, b
(ii) This means, global variable can be accessed
mycolor()
inside or outside of all the functions in a
print color
program. Consider the following example

20
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


1. a:=10 Entire program Output Entire program Library files
2. Disp(): a:=10 of the Built in/module scope associated
3. a:=7 Disp( ): Program with the software

Scoping
a:=7
Disp( ):
4. print a print a 7
Disp 1( ):
5. Disp() Disp ( ): 10 print a
print a
6. print a Disp 1( )
print a

m
(iii) On execution of the above code the variable Disp( )
'a' which is defined inside the function
displays the value 7 for the function call LEGB rule : [May-'22]

co
Disp() and then it displays 10, because a is
The LEGB rule is used to decide the order
defined in global scope.
in which the scopes are to be searched
Enclosed Scope : for scope resolution. The scopes are listed
(i) All programming languages permit below in terms of hierarchy (highest to

.
functions to be nested. A function (method) lowest).

ks
with in another function is called nested
Local(L) Defined inside function/
function.
class
(ii) A variable which is declared inside a
Enclosed(E) Defined inside enclosing
function which contains another function
functions (Nested
oo
definition with in it, the inner function
function concept)
can also access the variable of the outer
function. This scope is called enclosed Global(G) Defined at the uppermost
scope. level
Built-in(B) Reserved names in built-
ab

(iii) When a compiler or interpreter search for a


variable in a program, it first search Local, in functions (modules)
and then search Enclosing scopes. Consider
BUILT-IN
the following example
ur

1. Disp(): Entire program Output GLOBAL

2. a:=10 of the ENCLOSED


Disp( ):
3. Disp1(): a:=10 Program LOCAL
Disp 1( ):
.s

4. print a print a 10
Disp 1( )
5. Disp1() print a 10
6. print a Disp( )
w

2. Write any Five Characteristics of Modules.


7. Disp()
 [PTA-4, 6; HY-2019; Sep-2020]
(iv) In the above example Disp1() is defined
Ans. The following are the desirable characteristics of
with in Disp(). The variable ‘a’ defined in
w

a module.
Disp() can be even used by Disp1() because
it is also a member of Disp(). (i) Modules contain instructions, processing
logic, and data.
Built-in Scope :
w

[FRT-'22]
(ii) Modules can be separately compiled and
(i) The built-in scope has all the names that are
stored in a library.
pre-loaded into the program scope when
we start the compiler or interpreter. (iii) Modules can be included in a program.
(ii) Any variable or function which is defined (iv) Module segments can be used by invoking
in the modules of a programming language a name and some parameters.
has Built-in or module scope. Consider the (v) Module segments can be used by other
following example. modules.

21
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit I - Chapter 3

3.
Sura’s

programming.
Available at All Leading Bookstores

➠ XII Std - Computer Science


Write any five benefits in using modular
[Govt. MQP-2019]
 

sum2()
num1:= num1 + 10
Ans. (i) Less code to be written. sum2()
(ii) A single procedure can be developed for sum1()
reuse, eliminating the need to retype the num1:= 10
code many times. sum()
(iii) Programs can be designed more easily Print num 1

m
because a small team deals with only a
small part of the entire code. PTA Questions and Answers
(iv) Modular programming allows many

co
programmers to collaborate on the same
1 MARK
application. 1. A variable which is declared inside a function
(v) The code is stored across multiple files.
which contains another function definition :
 [PTA-1]

.
(vi) Code is short, simple and easy to
(a) Local (b) Global
understand.

ks
(c) Enclosed (d) Built-in
(vii) Errors can easily be identified, as they are
 [Ans. (c) Enclosed]
localized to a subroutine or function.
2. Which are loaded as soon as the library files
(viii) The same code can be used in many
are imported to the program? [PTA-3]
applications.
oo
(a) Built-in scope variables
(ix) The scoping of variables can easily be (b) Enclosed scope variables
controlled. (c) Global scope variables

Hands on Practice (d) Local scope variables


ab

 [Ans. (a) Built-in scope variables]


1. Observe the following diagram and Write the 3. Which of the following is not the example of
pseudo code for the following. modules? [PTA-5]
(a) procedures (b) subroutines
ur

(c) class (d) functions


sum( )  [Ans. (c) class]
num1:=20
.s

sum1( ) 2 MARKS
num1:=num1 + 10 1. What are modules?  [PTA-4]
sum2( ) Ans. A module is a part of a program. Programs
w

num1: = num1 + 10 are composed of one or more independently


developed modules.
sum2( )
w

Government Exam Questions and Answers


sum1( )
1 MARK
w

num1:=10 The kind of scope of the variable 'a' used in the


1.
sum( ) pseudo code given below. [Govt. MQP-2019]
print num1 (a) Disp(): (b) a: = 7
Ans. sum():
(c) print a (d) Disp()
num 1:=20 (a) Local (b) Global
sum1() (c) Enclosed (d) Built-in
num1:= num1 + 10 [Ans. (a) Local]

22
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Chapter

Available at All Leading Bookstores

   
4 ALGORITHMIC STRATEGIES

m
. co
CHAPTER SNAPSHOT

ks
4.1 Introduction to Algorithmic strategies
4.1.1. Characteristics of an Algorithm
4.1.2. Writing an Algorithm
oo
4.1.3. Analysis of Algorithm
4.2 Complexity of an Algorithm
4.2.1. Time Complexity
4.2.2. Space Complexity
ab

4.3 Efficiency of an algorithm


4.3.1. Method for determining Efficiency
4.3.2. Space-Time tradeoff
4.3.3. Asymptotic Notations
ur

4.3.4. Best, Worst, and Average ease Efficiency


4.4 Algorithm for Searching Techniques
4.4.1. Linear Search
.s

4.4.2. Binary Search


4.5 Sorting Techniques
4.5.1. Bubble sort algorithm
w

4.5.2. Selection sort


4.5.3. Insertion sort
w

4.6 Dynamic programming


4.6.1. Fibonacci Series – An example
4.6.2. Fibonacci Iterative Algorithm with Dynamic programming approach
w

[28]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science

Evaluation 9. If a problem can be broken into subproblems


which are reused several times, the problem

Algorithmic strategies
possesses which property?
Part - I
(a) Overlapping subproblems
Choose the best answer  (1 mark) (b) Optimal substructure
1. The word comes from the name of a Persian
mathematician Abu Ja’far Mohammed ibn-i (c) Memoization

m
Musa al Khowarizmi is called? (d) Greedy
 [PTA-6; Aug-2021; May-'22] [Ans. (a) Overlapping subporblems]
(a) Flowchart (b) Flow 10. In dynamic programming, the technique of

co
(c) Algorithm (d) Syntax storing the previously calculated values is
[Ans. (c) Algorithm] called ? [HY-2019]
2. From the following sorting algorithms which
(a) Saving value property
algorithm needs the minimum number of
swaps? [FRT-'22]
(b) Storing value property

.
(a) Bubble sort (b) Insertion sort (c) Memoization

ks
(c) Selection sort (d) All the above (d) Mapping [Ans. (c) Memoization]
[Ans. (c) Selection sort] Part - II
3. Two main measures for the efficiency of an
algorithm are [Mar.-2020]
Answer the following questions
oo
(a) Processor and memory  (2 marks)
(b) Complexity and capacity
(c) Time and space (d) Data and space 1. What is an Algorithm? [Mar.-2020; Aug-2021]
[Ans. (c) Time and space] Ans. An algorithm is a finite set of instructions to
ab

4. The complexity of linear search algorithm is accomplish a particular task. It is a step-by-step


(a) O(n) (b) O(log n) procedure for solving a given problem.
(c) O(n2) (d) O(n log n) 2. Define Pseudo code.
[Ans. (a) O(n)] Ans. (i) Pseudo code is an informal high level
ur

5. From the following sorting algorithms which description of the operations principle of a
has the lowest worst case complexity? computer program or other algorithm.
(a) Bubble sort (b) Quick sort
(ii) It uses the structural conventions of a
.s

(c) Merge sort (d) Selection sort normal programming language, but is
[Ans. (c) Merge sort] intended for human reading rather than
6. Which of the following is not a stable sorting machine reading.
w

algorithm? 3. What is Insertion sort?


(a) Insertion sort (b) Selection sort
Ans. (i) Insertion sort is a simple sorting algorithm.
(c) Bubble sort (d) Merge sort
(ii) It works by taking elements from the list
w

[Ans. (b) Selection sort]


one by one and inserting then in their
7. Time complexity of bubble sort in best case is
correct position in to a new sorted list.
 [PTA-1]
(iii) This algorithm builds the final sorted array
w

(a) θ (n) (b) θ (nlogn)


at the end.
(c) θ (n2) (d) θ (n(logn) 2)
[Ans. (a) θ (n)] 4. What is Sorting? [FRT-'22]
8. The Θ notation in asymptotic evaluation Ans. Sorting is any process of arranging information
represents or data in an ordered sequence either in
(a) Base case (b) Average case ascending or descending order. Various sorting
techniques in algorithms are Bubble sort, Quick
(c) Worst case (d) NULL case
sort, Heap sort, Selection sort, Insertion sort.
[Ans. (b) Average case]
29
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit I - Chapter 4

5.

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


What is searching? Write its types.
[Govt. MQP-2019; HY-2019; May-'22]
4.

 
Write a note on Asymptotic notation.
[QY-2019; Mar.-2020]
Ans. A searching algorithm is the step-by-step Ans. Asymptotic Notations are languages that uses
procedure used to locate specific data among
meaningful statements about time and space
a collection of data. There are two type of
searching are complexity. The following three asymptotic
(i) Linear Search
notations are mostly used to represent time

m
complexity of algorithms:
(ii) Binary Search
(i) Big O : Big O is often used to describe the
Part - III worst-case of an algorithm.
Answer the following questions

co
(ii) Big Ω : Big Omega is the reverse Big O, if
 (3 marks) Bi O is used to describe the upper bound
1. List the characteristics of an algorithm. (worst - case) of a asymptotic function, Big
Ans. (i) Input [Aug-2021; May-'22] Omega is used to describe the lower bound

.
(best-case).

ks
(ii) Output
(iii) Finiteness (iii) Big Θ : When an algorithm has a complexity
(iv) Definiteness with lower bound = upper bound, say that
an algorithm has a complexity O (n log
(v) Effectiveness
oo n) and Ω (n log n), it’s actually has the
(vi) Correctness
complexity Θ (n log n), which means the
(vii) Simplicity running time of that algorithm always falls
(viii) Unambiguous in n log n in the best-case and worst-case.
ab

(ix) Feasibility 5. What do you understand by Dynamic


(x) Portable programming? [Sep-2020]
(xi) Independent
Ans. (i) Dynamic programming is an algorithmic
design method that can be used when the
ur

2. Discuss about Algorithmic complexity and its


types. [PTA-1] solution to a problem can be viewed as the
Ans. The complexity of an algorithm f (n) gives the result of a sequence of decisions.
running time and/or the storage space required
.s

(ii) Dynamic programming approach is similar


by the algorithm in terms of n as the size of input
data. to divide and conquer. The given problem
(i) Time Complexity : The Time complexity is divided into smaller and yet smaller
w

of an algorithm is given by the number of possible sub-problems.


steps taken by the algorithm to complete (iii) Dynamic programming is used whenever
the process.
problems can be divided into similar
w

(ii) Space Complexity : Space complexity sub-problems. So that their results can be
of an algorithm is the amount of memory
required to run to its completion. re-used to complete the process.
w

3. What are the factors that influence time and (iv) Dynamic programming approaches are
space complexity? used to find the solution in optimized way.
For every inner sub problem, dynamic
Ans. (i) Time Factor -Time is measured by
counting the number of key operations like algorithm will try to check the results of
comparisons in the sorting algorithm. the previously solved sub-problems. The
solutions of overlapped sub-problems are
(ii) Space Factor - Space is measured by the
maximum memory space required by the combined in order to get the better solution.
algorithm.

30
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

 

6
Chapter
CONTROL STRUCTURES
CHAPTER SNAPSHOT

m
6.1 Introduction 6.2.2 Alternative or Branching Statement

co
6.2 Control Structures 6.2.3. Iteration or Looping constructs
6.2.1 Sequential Statement 6.2.4 Jump Statements in Python

Evaluation 7. What is the output of the following snippet?


i=1

.
while True:
Part - I

ks
if i%3 ==0:
Choose the best answer  (1 mark) break
1. How many important control structures are print(i,end='')
there in Python? [SRT-'22] i +=1
(a) 3 (b) 4 (c) 5
oo (d) 6
(a) 12 (b) 123 (c) 1234 (d) 124
 [Ans. (a) 12]
 [Ans. (a) 3] 8. What is the output of the following snippet?
2. elif can be considered to be abbreviation of T=1
 [May-'22] while T:
ab

(a) nested if (b) if..else print(True)


(c) else if (d) if..elif break
 [Ans. (c) else if] (a) False (b) True
3. What plays a vital role in Python (c) 0 (d) 1
 [Ans. (b) True]
ur

programming? [Aug-2021]
9. Which amongst this is not a jump statement ?
(a) Statements (b) Control (a) for (b) pass
(c) Structure (d) Indentation (c) continue (d) break
 [Ans. (d) Indentation]  [Ans. (a) for]
.s

4. Which statement is generally used as a 10. Which punctuation should be used in the
placeholder? blank?
(a) continue (b) break if <condition>_
w

(c) pass (d) goto statements-block 1


 [Ans. (c) pass] else:
statements-block 2
5. The condition in the if statement should be in
w

(a) ; (b) : (c) :: (d) !


the form of
[Ans. (b) :]
(a) Arithmetic or Relational expression
(b) Arithmetic or Logical expression
Part - II
Answer the following questions
w

(c) Relational or Logical expression


(d) Arithmetic  (2 marks)
 [Ans. (c) Relational or Logical expression] 1. List the control structures in Python. [PTA-6]
6. Which is the most comfortable loop? [July-'22] Ans. There are three important control structures are,
(a) do..while (b) while (i) Sequential
(c) for (d) if..elif (ii) Alternative or Branching
 [Ans. (c) for] (iii) Iterative or Looping
[61]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit II - Chapter 6

2.
Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


Write note on break statement. 
Ans. The break statement terminates the loop
[Aug-2021]
 
(iii) Syntax:
if <condition>:
containing it. Control of the program flows to statements-block 1
the statement immediately after the body of the else:
loop. statements-block 2
3. Write is the syntax of if..else statement 3. Using if..else..elif statement write a suitable
Ans. Syntax : [SRT-'22] program to display largest of 3 numbers.

m
if <condition>: Ans. Code :
statements-block 1 n1=int(input(:Enter the first number:"))
else: n2=int(input("Enter the second number:"))

co
statements-block 2 n3=int(input(:Enter the third number:"))
4. Define control structure. [PTA-2] if(n1?=n2)and(n1>=n3):
Ans. A program statement that causes a jump of biggest=n1;
control from one part of the program to another elif(n2>=n1)and (n2>=n3):

.
is called control structure or control statement. biggest=n2

ks
5. Write note on range () in loop. else:
 [PTA-2; March-2020; July-'22] biggest=n3
Ans. range() generates a list of values starting from print("The biggest number
start till stop-1. between",n1,",",n2,"and",n3,"is",biggest)
oo
The syntax of range() is as follows: Output :
range (start,stop,[step]) Enter the first number:1
Where, Enter the second number:3
start – refers to the initial value Enter the third number:5
ab

stop – refers to the final value The biggest number between 1,3 and 5 is 5
step – refers to increment value, this is optional
part. 4. Write the syntax of while loop.
 [PTA-4; QY-2019; SRT & July-'22]
Part - III Ans. Syntax:
ur

Answer the following questions while <condition>:


 (3 marks) statements block 1
1. Write a program to display [PTA-5; May-'22] [else:
.s

A statements block2]
AB 5. List the differences between break and
ABC continue statements. [HY-2019; May-'22]
w

ABCD
ABCDE Ans. Break Continue
Ans. for i in range (1, 6): The break statement The continue
w

for j in range (65, 65 + i) terminates the loop statement is used to


a=chr(j) containing it. skip the remaining
print a part of a loop.
w

print Control of the Control of the


2. Write note on if..else structure. program flows program flows start
to the statement with next iteration.
Ans. (i) The if.. else statement provides control to
immediately after the
check the true block as well as the false
block. body of the loop.
(ii) if..else statement thus provides two Syntax : break Syntax : continue
possibilities and the condition determines
which BLOCK is to be executed.
62
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


Part - IV for each item
Answer the following questions

Control Structures
in sequence
 (5 marks)
1. Write a detail note on for loop. Yes
[Govt. MQP-2019; Aug-2021; SRT, May & July-'22] Last item

m
Ans. (i) for loop : for loop is the most comfortable
reached?
loop. It is also an entry check loop. The
condition is checked in the beginning and

co
the body of the loop(statements-block 1)
is executed if it is only True otherwise the No
loop is not executed.
(ii) Syntax: Body of for

.
for counter_variable in sequence:

ks
statements-block 1 Exit loop
[else: # optional block for loop execution
statements-block 2]
Example :
(iii) The counter_variable mentioned in the
oo #Program to illustrate the use of for loop - to
syntax is similar to the control variable
that we used in the for loop of C++ and print single digit even number
the sequence refers to the initial, final for i in range (2,10,2):
and increment value. Usually in Python, print (i, end=' ')
ab

for loop uses the range() function in the Output :


sequence to specify the initial, final and 2468
increment values. range() generates a list of
values starting from start till stop-1. 2. Write a detail note on if..else..elif statement
ur

(iv) The syntax of range() is as follows: with suitable example. [HY-2019; Sep-2020]
range (start,stop,[step]) Ans. Nested if..elif...else statement :
Where, (i) When we need to construct a chain of if
start – refers to the initial value statement(s) then 'elif' clause can be used
.s

stop – refers to the final value instead of 'else'.


step – refers to increment value, this is (ii) Syntax :
w

optional part. if <condition-1>:


Examples for range() : statements-block 1
range (1,30,1) - will start the range of values
elif <condition-2>:
w

from 1 and end at 29


statements-block 2
range (2,30,2) - will start the range of values else:
from 2 and end at 28
w

statements-block n
range (30,3,-3) - will start the range of values
(iii) In the syntax of if..elif..else mentioned
from 30 and end at 6 above, condition-1 is tested if it is true then
range (20) - will consider this value 20 as statements-block1 is executed, otherwise
the end value(or upper limit) the control checks condition-2, if it is true
and starts the range count statements-block2 is executed and even if it
from 0 to 19 (remember fails statements-block n mentioned in else
always range() will work till part is executed.
stop -1 value only)
63
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit II - Chapter 6

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science

Test
 
Output 2 :
Enter mark in first subject : 67
false
Expression
of if Enter mark in second subject : 73
Grade : B
True Test 3. Write a program to display all 3 digit odd
false
Body of if
Expression
of elif numbers.

m
True Ans. for a in range (100, 1000):
if a %2==1:
print b

co
Body of else
Body of elif

Output :
if..elif..else statement execution
101, 103, 105, 107 ... .... 997, 999

(iv) 'elif' clause combines if..else-if..else 4. Write a program to display multiplication

.
statements to one if..elif…else. 'elif' can table for a given number.

ks
be considered to be abbreviation of 'else if'. Ans. Multiplication table :
In an 'if' statement there is no limit of 'elif '
num = int(input("Enter the number : "))
clause that can be used, but an 'else' clause
if used should be placed at the end. prit("multiplication Table of ", num)
oo for i in range(1,11):
(v) Example : #Program to illustrate the use of
nested if statement print (num, "x", i, " = ", num*i)
Average Grade Output :
Enter the number : 6
ab

>=80 and above A


Multiplication Table of 6
>=70 and <80 B
6×1=6
>=60 and <70 C
6 × 2 = 12
>=50 and <60 D 6 × 3 = 18
ur

Otherwise E 6 × 4 = 24
m1=int (input("Enter mark in first subject : ")) 6 × 5 = 30
m2=int (input("Enter mark in second subject : ")) 6 × 6 = 36
.s

avg= (m1+m2)/2 6 × 7 = 42
if avg>=80: 6 × 8 = 48
print ("Grade : A") 6 × 9 = 54
w

elif avg>=70 and avg<80: 6 × 10 = 60


print ("Grade : B")
elif avg>=60 and avg<70: Hands on Experience
w

print ("Grade : C")


1. Write a program to check whether the given
elif avg>=50 and avg<60:
character is a vowel or not. [QY-2019]
w

print ("Grade : D")


Ans. Program :
else:
print ("Grade : E") ch = input ("Enter a character")
Output 1: if ch in ('a', 'A', 'e', 'E', 'i', 'I','o','O','u', 'U'):
Enter mark in first subject : 34 print (ch, 'is a vowel')
Enter mark in second subject : 78 else :
Grade : D print (ch, 'the letter is not a vowel')

64
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

 
STRINGS AND

8
Chapter
STRING MANIPULATION

m
CHAPTER SNAPSHOT
8.1 Introduction 8.6 String Formatting Operators

co
8.2 Creating Strings 8.7 Formatting characters
8.3 Accessing characters in a String 8.8 The format( ) function
8.4 Modifying and Deleting Strings 8.9 Built-in String functions
8.5 String Operators 8.10 Membership Operators

.
ks
Evaluation 5. Strings in python:
(a) Changeable (b) Mutable
[Aug-2021]

(c) Immutable (d) flexible


Part - I
oo  [Ans. (c) Immutable]
Choose the best answer  (1 mark) 6. Which of the following is the slicing operator?
1. Which of the following is the output of the
 [PTA-1]
following python code?
(a) { } (b) [ ] (c) < > (d) ( )
ab

str1="TamilNadu"
 [Ans. (b) [ ]]
print(str1[::–1])
7. What is stride? [PTA-2; July-'22]
(a) Tamilnadu (b) Tmlau
(a) index value of slide operation
(c) udanlimaT (d) udaNlimaT
ur

(b) first argument of slice operation


 [Ans. (d) udaNlimaT]
(c) second argument of slice operation
2. What will be the output of the following code?
(d) third argument of slice operation
str1 = "Chennai Schools"
.s

 [Ans. (d) third argument of slice operation]


str1[7] = "-"~ [May-'22]
8. Which of the following formatting character
(a) Chennai-Schools (b) Chenna-School is used to print exponential notation in upper
w

(c) Type error (D) Chennai case? [PTA-5]


 [Ans. (c) Type error] (a) %e (b) %E (c) %g (d) %n
3. Which of the following operator is used for  [Ans. (b) %E]
w

concatenation? [SRT-'22] 9. Which of the following is used as placeholders


or replacement fields which get replaced along
(a) + (b) & (c) * (d) =
with format( ) function? [PTA-4]
w

 [Ans. (a) +]
(a) { } (b) < > (c) ++ (d) ^^
4. Defining strings within triple quotes allows  [Ans. (a) { }]
creating: [HY-2019] 10. The subscript of a string may be:
(a) Single line Strings (b) Multiline Strings (a) Positive (b) Negative
(c) Double line Strings (d) Multiple Strings (c) Both (a) and (b) (d) Either (a) or (b)
 [Ans. (b) Multiline Strings]  [Ans. (d) Either (a) or (b)]

[99]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit II - Chapter 8

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


Part - II
Answer the following questions
 
(ii) Thus, [] is also known as slicing operator.
Using slice operator, you have to slice one
or more substrings from a main string.
 (2 marks) General format of slice operation :
Str[start : end]
1. What is String?  [Aug-2021; SRT-'22]
Ans. (i) String is a data type in python, which is Part - III
used to handle array of characters. Answer the following questions

m
(ii) String is a sequence of Unicode characters
that may be a combination of letters,
 (3 marks)
numbers, or special symbols enclosed 1. Write a Python program to display the given

co
within single, double or even triple quotes. pattern. [Govt. MQP-2019]
(iii) Example : COMPUTER
'Welcome to learning Python' COMPUTE
COMPUT
"Welcome to learning Python" COMPU

.
" "Welcome to learning Python" " COMP

ks
2. Do you modify a string in Python? COM
Ans. (i) Yes we can modify the string by the CO
following method. C
(ii) A new string value can be assign to the Ans. str1 = "COMPUTER"
existing string variable.
oo index = len(str1)
(iii) When defining a new string value to the for i in str1:
existing string variable. print (str1[: index])
(iv) Python completely overwrite new string on index – = 1
the existing string.
ab

2. Write a short about the followings with


3. How will you delete a string in Python?
suitable example:
Ans. Python will not allow deleting a particular
(a) capitalize( ) (b) swapcase( )
character in a string. Whereas you can remove
entire string variable using del command.  [PTA-1, 3; Sep-2020]
ur

>>> str1="How about you" Ans.


>>> print (str1) Descrip
Syntax Example
How about you tion
.s

>>> del str1 (a) capitalize( ) Used to >>> city="chennai"


>>> print (str1) capitalize >>> print(city.
Traceback (most recent call last): the first capitalize())
w

File "<pyshell#14>", line 1, in <module> character Chennai


print (str1) of the
NameError: name 'str1' is not defined string
w

4. What will be the output of the following (b) swapcase( ) It will >>> str1="tAmiL
python code? [July-'22] change NaDu"
str1 = "School" case of
w

>>> print(str1.
print(str1*3) every swapcase())
Ans. Output : School School School character TaMIl nAdU
5. What is slicing? [PTA-6; Aug-2021] to its
Ans. (i) Slice is a substring of a main string. A opposite
substring can be taken from the original case vice-
string by using [] operator and index or versa.
subscript values.

100
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


3. What will be the output of the given python Part - IV
program?

Strings and String Manipulation


str1 = "welcome" Answer the following questions
str2 = "to school"  (5 marks)
str3 = str1[:2]+str2[len(str2)-2:] 1. Explain about string operators in python with
print(str3) suitable example. [PTA-2; HY-2019; SRT-'22]
Ans. weol Ans. String Operators : Python provides the

m
following operators for string operations. These
4. What is the use of format( )? Give an example. operators are useful to manipulate string.
 [HY-2019]
(i) Concatenation (+) : Joining of two or more
Ans. (i) The format( ) function used with strings is strings is called as Concatenation. The plus

co
very versatile and powerful function used (+) operator is used to concatenate strings
for formatting strings. in python.
(ii) The curly braces { } are used as placeholders Example :
or replacement fields which get replaced >>> "welcome" + "Python"
along with format( ) function.

.
'welcomePython'
(iii) Example : (ii) Append (+ =) : Adding more strings at

ks
num1=int (input("Number 1: ")) the end of an existing string is known as
num2=int (input("Number 2: ")) append. The operator += is used to append
print ("The sum of {} and {} is {}". a new string with an existing string.
format(num1,num2,(num1+num2))) Example :
Output :
oo >>> str1="Welcome to "
Number 1: 34 >>> str1+="Learn Python"
Number 2: 54 >>> print (str1)
The sum of 34 and 54 is 88 Welcome to Learn Python
ab

(iii) Repeating (*) : The multiplication operator


5. Write a note about count( ) function in python. (*) is used to display a string in multiple
Ans. number of times.
Syntax Description Example Example :
>>> str1="Welcome "
ur

count Returns the >>> str1="Raja Raja >>> print (str1*4)


(str, beg, number of Chozhan" Welcome Welcome Welcome Welcome
end) substrings >>> print(str1. (iv) String slicing :
occurs count('Raja')) ■ Slice is a substring of a main string.
.s

within the 2 ■ A substring can be taken from the original


given range. >>> print(str1. string by using [ ] slicing operator and
Remember count('r')) index values.
w

that substring 0 ■ Using slice operator, you have to slice one


or more substrings from a main string.
may be a single >>> print(str1.
General format of slice operation :
w

character. count('R')) str[start:end]


Range (beg 2 ■ Where start is the beginning index and
and end) >>> print(str1. end is the last index value of a character in
w

arguments count('a')) the string.


are optional. 5 ■ Python takes the end value less than one
If it is not >>> print(str1. from the actual index specified.
Example :
given, python count('a',0,5))
slice a single character from a string
searched in 2
>>>str1="THIRUKKURAL"
whole string. >>> print(str1. >>>print (str1[0])
Search is case count('a',11)) Output :
sensitive. 1 T
101
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

 
Chapter PYTHON CLASSES AND
10 OBJECTS

m
co
CHAPTER SNAPSHOT
10.1 Introduction
10.2 Defining classes
10.3 Creating Objects

.
ks
10.4 Accessing Class Members
10.5 Class Methods
10.6 Constructor and Destructor in Python
10.7 Public and Private Data Members
oo
Evaluation 5. A private class variable is prefixed with
(a) __ (b) && (c) ## (d) **
 [Ans. (a) __]
ab

Part - I
6. Which of the following method is used as
Choose the best answer  (1 mark) destructor? [PTA-1; QY-2019; May-'22]
1. Which of the following are the key features of (a) __init__( ) (b) __dest__( )
(c) __rem__( ) (d) __del__( )
ur

an Object Oriented Programming language?


(a) Constructor and Classes  [Ans. (d) __del__( )]
(b) Constructor and Object
7. Which of the following class declaration is
(c) Classes and Objects
.s

correct? [PTA-6; Sep-2020]


(d) Constructor and Destructor
 [Ans. (c) Classes and Objects] (a) class class_name
(b) class class_name<>
2. Functions defined inside a class: (c) class class_name:
w

(a) Functions (b) Module (d) class class_name[ ]


(c) Methods (d) section  [Ans. (c) class class_name:]
 [Ans. (c) Methods]
w

8. Which of the following is the output of the


3. Class members are accessed through which following program?
operator? [Mar.-2020; SRT & July-'22] class Student:
w

(a) & (b) . (c) # (d) %


def __init__(self, name):
 [Ans. (b) . ]
self.name=name
4. Which of the following method is automatically print (self.name)
executed when an object is created?
S=Student(“Tamil”)
(a) __object__( ) (b) __del__( )
(a) Error (b) Tamil
(c) __func__( ) (d) __init__( )
 [Ans. (d) __init__( )] (c) name (d) self
 [Ans. (b) Tamil]
[139]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10

9.
Sura’s

variable?
Available at All Leading Bookstores

➠ XII Std - Computer Science


Which of the following is the private class
[PTA-2]
 
(ii) Constructor function will automatically
executed when an object of a class is created.
(a) __num (b) ##num General format of __init__ method
(c) $$num (d) &&num  (Constructor function)
 [Ans. (a) __num] def __init__(self, [args ……..]):
10. The process of creating an object is called as: <statements>
 [HY-2019; Aug-2021]
5. What is the purpose of Destructor?

m
(a) Constructor (b) Destructor
 [PTA-2; SRT-'22]
(c) Initialize (d) Instantiation
 [Ans. (d) Instantiation] Ans. (i) Destructor is also a special method gets
executed automatically when an object exit
Part - II

co
from the scope.
Answer the following questions (ii) In Python,_del_() method is used as
 (2 marks) destructor.
General format :
1. What is class? [PTA-1]

.
def_del_(self):

ks
Ans. (i) Class is the main building block in Python. <statements>
(ii) Class is a template for the object. Part - III
(iii) Object is a collection of data and function
that act on those data.
Answer the following questions
 (3 marks)
(iv) Objects are also called as instances of a
oo 1. What are class members? How do you define it?
class.
 [PTA-1; Aug-2021]
2. What is instantiation? [PTA-6; SRT-'22] Ans. Variables defined inside a class are called as “Class
Ans. Once a class is created, next to create an object Variable” and functions are called as “Methods”.
ab

or instance of that class. The process of creating Class variable and methods are together known
object is called as “Class Instantiation”. as members of the class. The class members
Syntax : should be accessed through objects or instance
Object_name = class_name( ) of class. A class can be defined anywhere in a
Python program.
ur

3. What is the output of the following program?


class Sample: Syntax for Defining a Class :
__num=10 class class_name :
def disp(self): statement_1
.s

print(self.__num) statement_2
S=Sample() ....................
S.disp() ....................
w

print(S.__num) statement_n
Ans. Output : 2. Write a class with two private class variables
>>> and print the sum using a method.
w

[PTA-2]
10
Ans. Code :
line 7, in <module>
class Sample :
print(S._num)
w

def_init_(self, n1, n2):


AttributeError : 'Sample' object has no attribute
'_num' self._n1=n1
>>> self._n2=n2
def sum(self):
4. How will you create constructor in Python?
print (“Class Variable 1:",self._n1)
"init" is a special function begin an end
Ans. (i) 
with double underscore in Python act as a print ("Class Variable 2:", self._n2)
Constructor. S=Sample (5,10)
S.sum()
140
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


Output : General format of constructor :
>>> def__init__(self, [args ................]):

Python Classes and Objects


Class Variable 1 : 5
<statements>
Class Variable 2 : 10
Sum : 15 Example : Program to illustrate Constructor
>>> class Sample:

m
3. Find the error in the following program to get def __init__(self, num):
the given output? print("Constructor of class Sample...")
class Fruits: self.num=num

co
def __init__(self, f1, f2):
print("The value is :", num)
self.f1=f1
self.f2=f2 S=Sample(10)
def display(self): Destructor :

.
print("Fruit 1 = %s, Fruit 2 = %s"

ks
(i) Destructor is also a special method gets
 %(self.f1, self.f2)) executed automatically when an object exit
F = Fruits ('Apple', 'Mango') from the scope.
del F.display
(ii) In Python, __del__() method is used as
F.display()
oo
destructor.
Output :
Fruit 1 = Apple, Fruit 2 = Mango General format of constructor :
Ans. In line No.8, del F.display will not come. def__del__(self):
ab

4. What is the output of the following program? <statements>


class Greeting: Example : Program to illustrate about the __
def __init__(self, name): del__( ) method
self.__name = name
ur

class Sample:
def display(self):
num=0
print("Good Morning ", self.__name)
obj=Greeting('Bindu Madhavan') def __init__(self, var):
.s

obj.display() [July-'22] Sample.num+=1


Ans. Good Morning Bindu Madhavan self.var=var
w

5. How to define constructor and destructor in print("The object value is = ", var)
Python? [PTA-4; Mar-2020; Sep-2020]
print("The value of class variable is=
Ans. Constructor :
w

", Sample.num)
(i) Constructor is the special function that
is automatically executed when an object def __del__(self):
of a class is created. In Python, there is a
w

Sample.num-=1
special function called “init” which act as a
print("Object with value %d is exit
Constructor.
from the scope"%self.var)
(ii) It must begin and end with double
underscore. S1=Sample(15)
(iii) Constructor function will automatically S2=Sample(35)
executed when an object of a class is created. S3=Sample(45)

141
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


Part - IV
Answer the following questions
  Hands on Experience
1. Write a program using class to store name and
 (5 marks) marks of students in list and print total marks.
1. Write a menu driven program to add or delete Ans. Class stud :
stationary items. You should use dictionary to def__init__(self):
store items and the brand. self.name=" "

m
Ans. Code : self.m1=0
stationary = {} self.m2=0
self.tot=0
print("\n1.Add Item \n2. Delete item \n3.Exit")
def gdata(self):

co
ch=int(input("\nEnter your choice:")) self.name = input("Enter your name")
while(ch==1) or (ch==2): self.m1 = int(input("Enter marks 1"))
if(ch==1) self.m2 = int(input("Enter marks 2"))
n=int(input("\nEnter the Number of self.tot = self.m1 + self.m2

.
def disp(self):
 Items to be added in the Dictionary:"))

ks
print(self.name)
for i in range(n): print(self.m1)
item=input("\nEnter an Item Name:") print(self.m2)
brand=input("\nEnter the Brand Name:") print(self.tot)
stationary[item]=brand
oo mlist = []
st = stud()
print(stationary) st. gdata()
elif(ch==2): mlist.append(st)
ritem=input("\nEnter the item to be for x in mlist :
ab

 removed from the Dictionary:") x. disp()


stationary.pop(ritem) Output :
Enter your name Ram
print(stationay)
Enter marks 1 100
ur

ch=int(input("\nEnter your choice:")) Enter marks 2 100


Output : Ram 100 100 200
1. Add Item 2. Write a program using class to accept three
sides of a triangle and print its area.
.s

2. Delete item
Ans. Class Tr:
3. Exit def__init__(self, a, b, c):
Enter your choice : 1 self.a = float(a)
w

Enter the Number of Items to be added in the slef.b = float(b)


 stationary shop : 2 self.c = float(c)
def area(self):
Enter an Item Name : Pen
w

s = (self.a + self.b + self.c)/2


Enter the Brand Name : Rorito return((s*(S.self.a)*(s.self.b)*(s.self.c)**0.5)
Enter an Item Name : Pencil a = input("Enter side 1 :")
w

Enter the Brand Name : Camlin b = input("Enter side 2 :")


{'Pen' : 'Rorito', 'Pencil' : 'Camlin'} c = input("Enter side 3 :")
ans = Tr(a,b,c)
Enter your choice : 2
print(ans.area())
Enter the item to be removed from the Dictionary Output :
 : Pen Enter side 1 : 3
{'Pencil': 'Camlin'} Enter side 2 : 4
Enter your choice : 3 Enter side 3 : 5
6.0
142
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


3. Write a menu driven program to read, display, Do you want to continue ..y
add and subtract two distances. 1. Accept

Python Classes and Objects


Ans. class Dist : 2. Display
def__init__(self): 3. Add
self.dist 1=0 4. Subtract
self.dist 2=0 Enter your choice : 2
def read(self):
Enter distance 1 : 100

m
self.dist 1 =int(input("Enter distance 1"))
Enter distance 2 : 75
sefl.dist 2 =int(input("Enter distance 2"))
Do you want to continue ..y
def disp(self):
print("distance 1", self.dist 1) 1. Accept

co
print("distance 2", self.dist 2) 2. Display
def add(self): 3. Add
print("Total distance", self.dist 1 + self.dist 4. Sub
2) Enter your choice : 4

.
def sub(self): Subtracted distance : 25

ks
print("Subtracted distance", self.dist 1-self. Do you want to continue .. N
dist 2)
d=Dist() PTA Questions and Answers
choi = "y"
while(choi =="y"):
oo 1 MARK
print("1. accept\n2. Display \n3. Total \n4. 1. In Python the class method must have which
Subtract")
named argument as first argument? [PTA-3]
ch = int(input("Enter your choice"))
(a) self (b) rec
if(ch==1):
ab

d.read() (c) global (d) key


elif(ch==2)  [Ans. (a) self]
d.disp() 2. The function defined inside a class is called as
elif(ch==3): ______. [PTA-4]
ur

d.add() (a) Attribute (b) Parameter


elif(ch==4): (c) Arguments (d) Methods
d.sub()  [Ans. (d) Methods]
else:
.s

print("Invalid Input ...") 3. The symbol of project in relational algebra of


choi = input("Do you want to continue") DBMS : [PTA-5]
Output : (a) σ (b) П (c) ∩ (d) ∪
w

1. Accept  [Ans. (b) П]


2. Display
3. Add 2 MARKS
w

4. Subtract 1. Write the syntax of class instantiation.[PTA-5]


Enter your choice : 1 Ans. Syntax :
Enter distance 1 : 100
w

object_name = class_name()
Enter distance 2 : 75
Do you want to continue .. y Note that the class instantiation uses function
1. Accept notation. ie.class_name with.
2. Display 2. Write the general format of slicing operation.
3. Add  [PTA-6]
4. Subtract
Ans. General format of slice operation:
Enter your choice : 3
Total distances : 175 str[start:end]

143
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10

1.
Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


3 MARKS
What is Public and Private data member in
 

def count_lower(self):
for ch in self.string:
Python? [PTA-3; Sep-2020; SRT-'22]
if (ch.islower()):
Ans. (i) The variables which are defined inside the
self.lowercase+=1
class is public by default. These variables def count_vowels(self):
can be accessed anywhere in the program for ch in self.string:
using dot operator. if (ch in ('A', 'a', 'e', 'E', 'i', 'l',

m
(ii) A variable prefixed with double underscore  'o', 'O', 'u', 'U')):
becomes private in nature. These variables self.vowels+=1
can be accessed only within the class. def count_consonants(self):

co
v=('A', 'a', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U')
5 MARKS
for ch in self.string:
1. Find the output of the following Python code if ch not in v and ch.isalpha():
 [PTA-1] self.consonants+=1

.
class Sample: def count_space(self):
num=0

ks
for ch in self.string:
def __init__(self, var): if (ch==" "):
Sample.num+=1 self.spaces+=1
self.var=var def execute(self):
print("The object value is = ", var)
oo self.count_upper()
print("The count of object created self.count_lower()
 = ", Sample.num) self.count_vowels()
S1=Sample(15) self.count_consonants()
S2=Sample(35) self.count_space()
ab

S3=Sample(45) def display(self):


Ans. In the program, class variable num is shared by all print("The given string
three objects of the class Sample. It is initialized to contains...")
zero and each time an object is created, the num print("%d Uppercase
ur

is incremented by 1. Since, the variable shared by letters"%self.uppercase)


all objects, change made to num by one object is print("%d Lowercase
reflected in other objects as well. letters"%self.lowercase)
What will be the output of the following print(%d Vowels"%self.vowels)
.s

2.
Python code? [PTA-2] print("%d Consonants"%self.
class String consonants)
def__init__(self): print("%d Spaces"%self.spaces)
w

self.uppercase=0 S = String()
self.lowercase=0 S.getstr()
self.vowels=0 S.execute()
w

self.consonants=0 S.display()
self.spaces=0 Ans. Output :
w

self.string="" Enter a string : Welcome to Learn Computer


def getstr(self): Science
self.string= str(input("Enter a The given string contains....
 String: ")) 5 Uppercase letters
def count_upper(self): 24 Lowercaase letters
for ch in self.string: 12 Vowels
if (ch.isupper()): 17 Consonants
self.uppercase+=1 3 Spaces

144
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


3. Rewrite the following Python program to get 3 MARKS
the given output: [PTA-3]
1. What is the output of the following program?

Python Classes and Objects


OUTPUT :
class Greeting: [Govt. MQP-2019]
Enter Radius: 5
def__init__(self, name):
The area = 78.5 self.__name = name
The circumference = 34.10 def display(self):
CODE :

m
print("Good Morning", self.__name)
Class circle( ) obj=Greeting('Tamil Nadu')
pi=3.14 obj.display()
def__init__(self, radius):

co
Ans. Good Morning Tamil Nadu
self=radius
2. What is Constructor? [QY-2019]
DEF area(SELF):
Ans. Constructor is the special function that is
Return automatically executed when an object of a class
Circle.pi + (self.radius * 2)

.
is created. In Python, there is a special function

ks
Def circumference (self): called “init” which act as a Constructor. It must
Return 2*circle.pi * self.radius begin and end with double underscore. This
r = input("Enter radius= ") function will act as an ordinary function; but only
difference is, it is executed automatically when
c = circle(r)
the object is created. This constructor function
print "The Area: ", c.area( )
oo
can be defined with or without arguments. This
print("The circumference=", c) method is used to initialize the class variables.
Ans. Class circle: General format of __init__ method (Constructor
pi=3.14 function)
ab

def__init__(self, radius): def __init__(self, [args ……..]):


<statements>
self.radius = radius
3. Write a Python program to check and print if
def area(self): the given number is odd or even using class.
ur

return circle.pi*(self.radius**2) Ans. class Odd_Even: [HY-2019]


def circumference(self): def check(self, num):
return2*circle.pi*self.radius if num%2==0:
print(num," is Even number")
.s

r=int(input("Enter Radius:"))
c = circle(r) else:
print(num," is Odd number")
print("The Area= ", c.area( ))
n=Odd_Even()
w

print("The circumference = ", c.circumference) x = int(input("Enter a value: "))


Government Exam Questions and Answers n.check(x)
w

4. What is the output of the following program?


1 MARK class Greeting: [Govt. MQP-2019]
1. A variable prefixed with double underscore is def__init__(self, name):
w

 [Govt. MQP-2019] self.__name = name


(a) private def display(self):
(b) public print(“Good Morning”, self.__
name)
(c) protected
obj=Greeting(‘Tamil Nadu’)
(d) static[Ans. (a) private]
obj.display()
Ans. Output :
Good Morning Tamil Nadu

145
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10

5.
Sura’s


Available at All Leading Bookstores

➠ XII Std - Computer Science


Write the output of the following program.
[Mar-2020]
  The class members should be accessed
through objects or instance of class. A
class Hosting: class can be defined anywhere in a Python
def __init__(self, name): program.
self.__name = name Example:
def display(self):
class Sample:
print("Welcome to", self.__name)

m
obj=Hosting("Python Programming") x, y = 10, 20 # class variables
obj.display() In the above code, name of the class is Sample
Ans. Output : Welcome to Python Programming. and it has two variables x and y having the

co
initial value 10 and 20 respectively. To
6. What will be the output of the following
access the values defined inside the class,
program? [SRT-'22]
you need an object or instance of the class.
class stud:
m1, m2, m3 = 45, 91, 71 2. What will be the output of the following

.
def process(self) : program? [SRT-'22]

ks
sum = stud.m1 + stud.m2 + stud.m3 Class Sample :
avg = sum/3 num = 0
print("Total Marks = ", sum) def _ _init_ _(self, var):
print("Average Marks = ", avg) Sample.num + = 1
return
oo self.var = var
s. stud( ) print("The object value is = ", var)
s. process( ) print("The count of object created = ",
Ans. Total Marks = 207 Sample.num)
ab

Average Marks = 69.0 S1 = Sample(15)


S2 = Sample(35)
5 MARKS S3 = Sample(45)
1. How will you create the class, and objects in
python. Ans. The object value is = 15
ur

[QY-2019]
(or) The count of object created = 1
The object value is = 35
 How to define a class in Python? Explain with
example. [SRT-'22] The count of object created = 2
.s

Ans. (i) In Python, a class is defined by using the The object value is = 45
keyword class. Every class has a unique The count of object created = 3
name followed by a colon ( : ).
w

Syntax: additional questions and Answers


class class_name:
statement_1 Choose the Correct Answer 1 MARK
w

statement_2 1. Which of the following is not an object


………….. oriented language?
………….. (a) C (b) C++
w

statement_n (c) Java (d) Python


(ii) 
Where, statement in a class definition  [Ans. (a) C]
may be a variable declaration, decision
2. Which of the following is called as instances
control, loop or even a function definition.
of a class ?
Variables defined inside a class are called as
(a) Methods (b) Objects
“Class Variable” and functions are called as
“Methods”. Class variable and methods are (c) Functions
together known as members of the class. (d) Datatypes [Ans. (b) Objects]

146
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


3. Functions of the class are called as 11. Which position of the argument named self in
(a) Methods python class method?

Python Classes and Objects


(b) Members (a) First (b) Second
(c) Variables (c) Third (d) Last
(d) Loog [Ans. (a) Methods]  [Ans. (a) First]

4. In Python, every class name followed by 12. Which argument doesn’t need a value when we
call the method?

m
(a) ; (b) : (c) : : (d) .
(a) this (b) self
 [Ans. (b) :] (c) var (d) first
5. Which of the following with a valid class  [Ans. (b) self]

co
definition? 13. Which of the following argument values
(a) Class classname () statement_1 automatically by python?
(b) Class classname : : statement_1 (a) self (b) this
(c) Class classname statement_1 (c) class (d) object
 [Ans. (a) self]

.
(d) Class classname statement_1
14. How many argument can be taken by Python

ks
 [Ans. (c) Class classname statement_1]
method even when a method is defined with
6. Which of the following is valid syntax for one argument?
crating objects? (a) 1 (b) 3 (c) 2 (d) 4
(a) objectname = classname ()  [Ans. (c) 2]
(b) objectname : classname ()
oo 15. Which of the following is automatically
(c) objectname = classname executed when an object of a class is created?
(d) classname = Objectname () (a) constructor (b) destructor
 [Ans. (c) objectname = classname] (c) class (d) members
ab

 [Ans. (a) constructor]


7. Which of the operator used to accessing 16. In Python, which function will act as a
members of the class? constructor?
(a) . (b) : (c) ; (d) , (a) int (b) inti
 [Ans. (a) .] (c) classname (d) init
ur

8. Which of the following can be accessed by  [Ans. (d) init]


using object with dot (.) operator? 17. In Python, constructor must begin and end
(a) List (b) Tuples with
.s

(c) Dictionary (d) None of these (a) _ _ and _ _ (b) _ _ and _ _


(c) + + and + + (d) + - and - +
 [Ans. (d) None of these]
 [Ans. (a) _ _ and _ _]
9. Which of the following is valid syntax of 18. Which of the following is used to initialize the
w

accessing class members class variables?


(a) objectname = classmember () (a) Destructor (b) Object
(b) objectname . classmember () (c) Constructor (d) Classmember
w

(c) objectname . classmember  [Ans. (c) Constructor]


(d) objectname . classmember 19. Which of the following gets executed
 [Ans. (b) objectname . classmember ()] automatically when an object exit from the
w

scope?
10. Write the output for the following (a) Destructor (b) Constructor
class test (c) Class (d) Object
x, y = 10, 5  [Ans. (a) Destructor]
s = test () 20. By default, the class variables are
print (s. x + s. y) (a) Private (b) Public
(a) 10 (b) 5 (c) 15 (d) 105 (c) Protected (d) Method
 [Ans. (c) 15]  [Ans. (b) Public]

147
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


21. Which of the following is a valid private
variable in python?
8.
 
The process of creating object is called as ____
(a) Class definition (b) Class declaration
(a) - i (b) i - (c) - - i (d) i - - (c) Class instantiation (d) Class objects
 [Ans. (c) - - i]  [Ans. (c) Class instantiation]
22. Which of the following variables can be 9. When class variable declared within class,
accessed only within the class? methods must be prefixed by the _______ and
(a) Protected (b) Public ______

m
(c) Private (d) None of these (a) classnam, : (b) classname, .
 [Ans. (d) None of these] (c) :, classname
(d) classname, objectname
Choose and filling the blanks

co
 [Ans. (b) classname, .]
1. ____ and ___ are the key features of object 10. Constructor must begin and with double
oriented programming. ______
(a) List and tuples (a) Colon (b) Semicolon
(b) Set and dictionary

.
(c) Dot (d) Underscore
(c) Classes and objects  [Ans. (d) Underscore]

ks
(d) Variables and methods
11. In Python, _____ method is used as destructor.
 [Ans. (c) Classes and objects]
(a) - - init - - () (b) - - des - - ()
2. ____ is the main building block in python. (c) - - del - - ()
(a) Objects (b) Methods
oo (d) - - destructor - - () [Ans. (b) - - des - - ()]
(c) Constructors (d) Class
12. A variable prefixed with _____ become private
 [Ans. (d) Class] in nature.
3. Class is a template for the _____ (a) double underscore (b) double colon
ab

(a) Method (b) Members (c) double dot (d) double hyphen
(c) Object (d) Destructor  [Ans. (a) double underscore]
 [Ans. (c) Object] Choose the correct statement
4. ______ may be a variable declaration, decision 1. (a) objectname.classmember()
control, loop or even a function definition.
ur

(b) objectname.classmember
(a) Class members (c) objectname().classmember
(b) Class instantiation (d) objectname : classmember
(c) Class method  [Ans. (b) objectname.classmember]
.s

(d) Class definition [Ans. (d) Class definition]


2. Which of the following is correct declaration
5. In Python, a class is defined by using the ____ of constructor?
class. (a) - - init - -
w

(a) Operator (b) Identifier (b) - - init - - ()


(c) Object (d) Keyword (c) - - classname - - ()
 [Ans. (d) Keyword] (d) - - classname - - () [Ans. (b) - - init - - ()]
w

6. Class variable and methods are together 3. (a) objectname = classname


known as ______ of the class. (b) objectname : classname ()
(a) Objects (b) Functions
w

(c) objectname = classname ()


(c) Statements (d) Members (d) objectname : : classname ()
 [Ans. (d) Members]  [Ans. (c) objectname = classname ()]
7. The ______ of the class should be accessed Choose the incorrect statement
through instance of a class.
1. (i) Th
 e process of creating object is called “Class
(a) Objects (b) Members
definition”
(c) Functions (d) Tuples
(ii) The class members are accessed using dot (.)
 [Ans. (b) Members] operator.

148
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


(iii) The first argument of the class method is not 5. Write a program in python that illustrate the
self. use of constructor.

Python Classes and Objects


(iv) The method argument defined with one Ans. Program to illustrate Constructor :
argument it takes two arguments with class Sample:
default. def __init__(self, num):
(a) i and iv (b) ii and iii print("Constructor of class Sample...")
(c) iv only (d) i and iii self.num=num

m
print("The value is :", num)
 [Ans. (d) i and iii]
S=Sample(10)
2. (i) C  onstructor executed automatically when
Short Answers 3 MARKS

co
the object is created
(ii) In Python, “init” which act as a destructor. 1. Write a note on object.
(iii) In Python, constructor can be defined only Ans. (i) Object is a collection of data and function
with arguments. that act on those data. Class is a template

.
(iv) Construct is used to initialize the class for the object.

ks
variables.
(ii) According to the concept of Object
(a) i and iii (b) ii and iv Oriented Programming, objects are also
(c) iii, iv and ii (d) ii and iii called as instances of a class.
 [Ans. (d) ii and iii]
(iii) In Python, everything is an object. For
oo
Very Short Answers 2 MARKS example, all integer variables that we use
1. Write the general form of declaring class in in our program is an object of class int.
Python. Similarly all string variables are also object
Ans. In Python, a class is defined by using the keyword
of class string.
ab

class. Every class has a unique name followed by 2. Write a note on self argument used in python
a colon ( : ). class function.
Syntax : Ans. (i) Python class function or Method is very
class class_name: similar to ordinary function with a small
ur

statement_1 difference that, the class method must have


statement_2 the first argument named as self.
…………..
(ii) No need to pass a value for this argument
…………..
.s

when we call the method. Python provides


statement_n
its value automatically.
2. Write the syntax for the following (iii) Even if a method takes no arguments, it
w

(i) Creating objects should be defined with the first argument


(ii) Accessing class members called self.
Ans. (i) Object – name = class_name () (iv) If a method is defined to accept only one
w

(ii) Object – name = class_member argument it will take it as two arguments ie.
3. Differentiate python class function and self and the defined argument.
ordinary function.
w

Ans. Python class function or method is very similar 3. Explain the working of the following program.
to ordinary function with a small difference. class Sample:
The class method must have the first argument def __init__(self, num):
named as self. print("Constructor of class
4. Name the function which acts as a constructor Sample...")
and destructor. self.num=num
Ans. Constructor -(- - init - - ( )) print("The value is :", num)
Destructor -(- - del - - ( )) S=Sample(10)

149
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10

Sura’s
Ans. (i)
Available at All Leading Bookstores

➠ XII Std - Computer Science


The above class “Sample”, has only a
constructor with one argument named as
 
Ans. 1. – y
2. – sample ()
num. When the constructor gets executed, 3. – s. x
first the print statement, prints the 4. – s. y
“Constructor of class Sample….”, then, the 5. – s. x + s. y
passing value to the constructor is assigned 6. Read the following program. Answer the
to self.num and finally it prints the value following question.

m
passed along with the given string. Class sample:
(ii) The above constructor gets executed x, y = 10, 20
automatically, when an object S is created s = sample ()

co
with actual parameter 10. Thus, the Python print (s. x + s. y)
displays the following output. 1. What does sample denotes?
(iii) Constructor of class Sample... 2. What does x, y denotes?
The value is : 10 3. What does s denotes?

.
Class variable defined within constructor Ans. 1. It denotes class name

ks
keep count of number of objects created 2. x, y is a class variables of the class
with the class. 3. S is an object created to access the members
4. Write a python program to find total and of the class
average marks using class. Long Answers 5 MARKS
oo
Ans. class Student: 1. Write a program to check and print if the given
number is negative or positive using class.
mark1, mark2, mark3 = 45, 91, 71
Ans. class test:
#class variable def check (self, num)
ab

def process(self): #class method if num> 0:


print (num, “is positive number”)
sum = Student.mark1 + Student.mark2 + else:
Student.mark3 print (num, “is negative number”)
n = test ()
ur

avg = sum/3 x = int (input(“Enter the number”))


print("Total Marks = ", sum) n. check (x)
print("Average Marks = ", avg) 2. Write a menu driven program that keeps
.s

record of books available in you school library.


return Ans. class Library:
S=Student() def __init__(self):
w

S.process() self.bookname=""
self.author=""
5. Fill up the blanks in the following program to def getdata(self):
w

get the output : self.bookname = input("Enter Name


Value of x = 10  of the Book: ")
Value of y = 20 self.author = input("Enter Author of
 the Book: ")
w

Sum of x and y = 30 def display(self):


Class sample: print("Name of the Book: ",self.bookname)
x, ____ = 10, 20 ------------------- print("Author of the Book: ",self.author)
s = ______ ------------------------- print(“\n”)
print (“value of x =”, _____) ------------- book=[] #empty list
ch = 'y'
print (“value of y =”, _____) -------------
while(ch=='y'):
print (“sum of x and y =”, _____) --------

150
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


print("1. Add New Book \n 2.Display print("-------------------------------------")
Books") for x in range(self.p):

Python Classes and Objects


resp = int(input("Enter your choice : ")) print(self.__prod_code[x], "\t\t", self.__
if(resp==1):  prod_name[x], "\t\t", self.__cost_
L=Library()
price[x])
L.getdata()
book.append(L) print("-------------------------------------")

m
elif(resp==2): def print_bill(self):
for x in book:
x.display() total_price = 0
else:

co
for x in range(self.p):
print("Invalid input....")
ch = input("Do you want continue....") q=int(input("Enter the quantify  for
3. Write a program to store product and its cost  the product code %d : "%self.__
price. Display all the available products and prod_code[x]))

.
prompt to enter quantity of all the products.

ks
self.__prod_quant.append(q)
Finally generate a bill which displays the total
amount to be paid. total_price = total_price +self.__cost_
Ans. class MyStore: price[x]*self.__prod_quant[x]
__prod_code=[]
oo print(" Invoice Receipt ")
__prod_name=[]
__cost_price=[] print("-------------------------------------")
__prod_quant=[] print("Product Code\t Product Name\t
def getdata(self):  Cost Price\t Quantity \t Total Amount")
ab

self.p = int(input("Enter no. of products


print("-------------------------------------")
 you need to store: "))
for x in range(self.p): for x in range(self.p):
self.__prod_code.
ur

print(self.__prod_code[x], "\t\t", self.__


 append(int(input("Enter Product Code: ")))  prod_name[x], "\t\t",
self.__prod_name.append(str(input("Enter
 Product Name: "))) self.__cost_price[x], "\t\t", self.__
.s

self.__cost_price.append(int(input("Enter  prod_quant[x], "\t\t",


 Cost price: "))) self.__prod_quant[x]*self.__cost_
def display(self): price[x])
w

print("Stock in Stores")
print("-------------------------------------")
print("-------------------------------------")
print("Product Code \t Product Name \t print(" Total Amount = ", total_price)
w

 Cost Price")
w



151
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

 
Chapter
PYTHON AND CSV FILES
13

m
co
CHAPTER SNAPSHOT
13.1 Introduction

.
13.2 Difference between CSV and XLS file formats

ks
13.3 Purpose of CSV File
13.4 Creating a CSV file using Notepad (or any text editor)
13.4.1 Creating CSV Normal File
13.4.2 Creating CSV File That contains Comma With Data
oo
13.4.3 Creating CSV File That contains Double Quotes With Data
13.4.4 Rules to be followed to format data in a CSV file
13.5 Create a CSV File using Microsoft Excel
13.5.1 Microsoft Excel to open a CSV file
ab

13.6 Read and Write a CSV file using Python


13.6.1 Read a CSV File Using Python
13.6.2 Read a specific column In a File
ur

13.6.3 Read A CSV File And Store It In A List


13.6.4 Read A CSV File And Store A Column Value In A List For Sorting
13.6.5 Sorting A CSV File With A Specified Column
13.6.6 Reading CSV File Into A Dictionary
.s

13.6.7 Reading CSV File With User Defined Delimiter Into A Dictionary
13.7 Writing Data into Different Types in Csv Files
13.7.1 Creating A New Normal CSV File
w

13.7.2 Modifying An Existing File


13.7.3 CSV Files With Quotes
w

13.7.4 CSV Files With Custom Delimiters


13.7.5 CSV File With A Line Terminator
13.7.6 CSV File with quote characters
w

13.7.7 Writing CSV File Into A Dictionary


13.7.8 Getting Data At Runtime And Writing It In a CSV File

[192]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science

Evaluation chennai,mylapore
mumbai,andheri

Python and Csv Files


Part - I (a) chennai,mylapore
(b) mumbai,andheri
Choose the best answer  (1 mark) (c) chennai
1. A CSV file is also known as a …. [Mar.-2020] mumbai
(d) chennai,mylapore

m
(a) Flat File (b) 3D File
mumbai,andheri
(c) String File (d) Random File
 [Ans. (b) mumbai,andheri]
 [Ans. (a) Flat File]
8. Which of the following creates an object which

co
2. The expansion of CRLF is maps data to a dictionary? [PTA-1]
 [Govt. MQP-2019; May-'22]
(a) listreader() (b) reader()
(a) Control Return and Line Feed
(c) tuplereader() (d) DictReader ()
(b) Carriage Return and Form Feed
 [Ans. (d) DictReader ()]

.
(c) Control Router and Line Feed

ks
(d) Carriage Return and Line Feed 9. Making some changes in the data of the
 [Ans. (d) Carriage Return and Line Feed] existing file or adding more data is called
3. Which of the following module is provided by (a) Editing (b) Appending
Python to do several operations on the CSV (c) Modification (d) Alteration
files?
oo
 [Ans. (c) Modification ]
(a) py (b) xls (c) csv (d) os
 [Ans. (c) csv] 10. What will be written inside the file test.csv
using the following program?
4. Which of the following mode is used when
ab

dealing with non-text files like image or exe import csv


files? [July-'22] D = [['Exam'],['Quarterly'],['Halfyearly']]
(a) Text mode (b) Binary mode csv.register_dialect('M',lineterminator = '\n')
(c) xls mode (d) csv mode with open('c:\pyprg\ch13\line2.csv', 'w') as f:
ur

 [Ans. (b) Binary mode] wr = csv.writer(f,dialect='M')


wr.writerows(D)
5. The command used to skip a row in a CSV file
is f.close()
(a) Exam Quarterly Halfyearly
.s

(a) next() (b) skip()


(c) omit() (d) bounce() (b) Exam Quarterly Halfyearly
 [Ans. (a) next()] (c) E (d) Exam,
w

Q Quarterly,
6. Which of the following is a string used to
H Halfyearly
terminate lines produced by writer()method
[Ans. (d) Exam,
of csv module?
Quarterly,
w

(a) Line Terminator (b) Enter key


Halfyearly]
(c) Form feed (d) Data Terminator
 [Ans. (a) Line Terminator] Part - II
w

7. What is the output of the following program? Answer the following questions
import csv  (2 marks)
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
1. What is CSV File? [PTA-3; Aug-2021; May-'22]
next(d)
Ans. (i) A CSV file is a human readable text file
for row in d:
where each line has a number of fields,
print(row)
separated by commas or some other
if the file called “city.csv” contain the following
delimiter.
details

193
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit IV - Chapter 13
Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


(ii) A CSV file is also known as a Flat File that
can be imported to and exported from
 
(ii) In this mode, while reading from the file
the data would be in the format of strings.
programs that store data in tables, such as
(iii) On the other hand, binary mode returns
Microsoft Excel or OpenOfficeCalc.
bytes and this is the mode to be used when
2. Mention the two ways to read a CSV file using dealing with non-text files like image or exe
Python. [PTA-2; Sep-2020]
files.
Ans. There are two ways to read a CSV file.

m
(a) Use the csv module’s reader function 2. Write a Python program to modify an existing
file. [July-'22]
(b) Use the DictReader class.
Ans. import csv

co
3. Mention the default modes of the File.
row = [‘3’, ‘Meena’,’Bangalore’]
Ans. (i) The default is reading ('r') in text mode.
with open(‘student.csv’, ‘r’) as readFile:
(ii) 
In this mode, while reading from the file
the data would be in the format of strings. reader = csv.reader(readFile)

.
lines = list(reader) # list()- to store each

ks
4. What is use of next() function?
 row of data as a list
Ans. (i) "next()" command is used to avoid or skip
the first row or row heading. lines[3] = row
(ii) Example : While sorting the row heading with open(‘student.csv’, ‘w’) as writeFile:
oo
is also get sorted, to avoid that the first is # returns the writer object which converts the user
skipped using next().  data with delimiter
(iii) Then the list is sorted and displayed. writer = csv.writer(writeFile)
ab

5. How will you sort more than one column from #writerows()method writes multiple rows to a csv
a csv file? Give an example statement. file
Ans. To sort by more than one column you can use writer.writerows(lines)
itemgetter with multiple indices: operator
readFile.close()
ur

.itemgetter (1,2).
Syntax : writeFile.close()
sortedlist = sorted(data, key=operator.itemget 3. Write a Python program to read a CSV file
.s

ter(Col_number),reverse=True) with default delimiter comma (,).


Example : sorted list = sorted (data, key = Ans. #import csv
operator.itemgetter(1))
import csv #opening the csv file which is in
w

 different location with read mode


Part - III
with open('c:\\pyprg\\sample1.csv','r') as F:
Answer the following questions
w

#other way to open the file is f=('c:\\


 (3 marks)
pyprg\\sample1.csv','r')
1. Write a note on open() function of python.
w

What is the difference between the two reader = csv.reader(F)


methods? [PTA-1; HY-2019; July-'22] #printing each line of the Data row
Ans. Python has a built-in function open() to open  by row
a file. This function returns a file object, also for row in reader
called a handle, as it is used to read or modify print(row)
the file accordingly.
F.close()
(i) The default is reading in text mode.

194
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science  


  
UNIT-V INTEGRATING PYTHON WITH MYSQL AND C++

m
Importing C++
Programs in Python

co
Chapter

14

.
ks
oo
CHAPTER SNAPSHOT
14.1 Introduction
14.2 Scripting Language
ab

14.2.1 Difference between Scripting and Programming Languages


14.3 Applications of Scripting Languages
14.4 Features of Python over C++
14.5 Importing C++ Files in Python
ur

14.5.1 MinGW Interface


14.5.2 Executing C++ Program through Python
14.6 Python Program to import C++
.s

14.6.1 Module
14.6.2 How to import modules in Python?
14.7 Python program Executing C++ Program using control statement
w

14.8 How Python is handling the errors in C++


14.9 Python program Executing C++ Program Containing Arrays
14.10 Python program Executing C++ Program Containing Functions
w

14.11 Python program to Illustrate the inheritance of a Class


w

[210]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science

Evaluation 8. Identify the function call statement in the


following snippet. [Govt. MQP-2019]

Importing C++ Programs in Python


if __name__ =='__main__':
Part - I main(sys.argv[1:])
(a) main(sys.argv[1:]) (b) __name__
Choose the best answer  (1 mark) (c) __main__ (d) argv
1. Which of the following is not a scripting  [Ans. (b)__name__]

m
language? 9. Which of the following can be used for
(a) JavaScript (b) PHP processing text, numbers, images, and
(c) Perl (d) HTML scientific data?

co
 [Ans. (d) HTML] (a) HTML (b) C
(c) C++ (d) PYTHON
2. Importing C++ program in a Python program
[Ans. (d) PYTHON]
is called [HY-2019]
(a) wrapping (b) Downloading 10. What does __name__ contains ? [PTA-6]

.
(c) Interconnecting (d) Parsing (a) c++ filename (c) main() name

ks
[Ans. (a) wrapping] (c) python filename (d) os module name
[Ans. (C) python filename]
3. The expansion of API is
(a) Application Programming Interpreter
Part - II
(b) Application Programming Interface Answer the following questions
oo
(c) Application Performing Interface  (2 marks)
(d) Application Programming Interlink 1. What is the theoretical difference between
[Ans. (b) Application Programming Scripting language and other programming
Interface] language? [Aug-2021]
ab

4. A framework for interfacing Python and C++ is Ans. (i) The theoretical difference between the two
 [Mar.-2020; May-'22] is that scripting languages do not require the
(a) Ctypes (b) SWIG compilation step and are rather interpreted.
(c) Cython (d) Boost (ii) For example, normally, a C++ program
ur

[Ans. (d) Boost] needs to be compiled before running


whereas, a scripting language like JavaScript
5. Which of the following is a software design or Python need not be compiled.
technique to split your code into separate (iii) A scripting language requires an interpreter
.s

parts? [PTA-5] while a programming language requires a


(a) Object oriented Programming compiler.
(b) Modular programming 2. Differentiate compiler and interpreter.
w

(c) Low Level Programming Ans.  [Govt. MQP-2019; July-'22]


(d) Procedure oriented Programming
S.No Compiler Interpreter
[Ans. (b) Modular programming]
w

(i) Compiler generates Interpreter


6. The module which allows you to interface with an Intermediate generates Machine
the Windows operating system is [Aug-2021] Code. Code.
w

(a) OS module (b) sys module (ii) Compiler reads Interpreter reads
(c) csv module (d) getopt module entire program for single statement
[Ans. (a) OS module] compilation. at a time for
interpretation.
7. getopt() will return an empty array if there is (iii) Error deduction is Error deduction is
no error in splitting strings to [July-'22] difficult. easy.
(a) argv variable (b) opt variable (iv) Comparatively faster. Slower.
(c) args variable (d) ifile variable (v) Example : C++ Example : Python
[Ans. (c) args variable]
211
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit V - Chapter 14

3.

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


Write the expansion of (i) SWIG (ii) MinGW
[PTA-1, 5; Mar.-2020]
 
(iii) Less code intensive as compared to
traditional programming language
Ans. (i) SWIG – Simplified Wrapper Interface (iv) can bring new functions to applications
Generator – Both C and C++. and glue complex systems together
(ii) MINGW – Minimalist GNU for Windows
3. What is MinGW? What is its use?
4. What is the use of modules? Ans. (i) MinGW refers to a set of runtime header

m
Ans. (i) The use of modules to break down large files, used in compiling and linking the
programs into small manageable and code of C, C++ and FORTRAN to be run
organized files. on Windows Operating System.

co
(ii) Modules provide reusability of code. Define (ii) MinGw-W64 (version of MinGW) is the
our most used functions in a module best compiler for C++ on Windows. To
and import it, instead of copying their compile and execute the C++ program, you
definitions into different programs. need ‘g++’ for Windows. MinGW allows

.
5. What is the use of cd command. Give an to compile and execute C++ program

ks
example. dynamically through Python program
Ans. ‘cd’ command refers to change directory and using g++.
absolute path refers to the complete path where (iii) Python program that contains the C++
python is installed.
oo coding can be executed through either by
(Eg) “cd:\>cd c:\program files\open office 4\ using command prompt or by using run
program”
terminal.
Part - III 4. Identify the module, operator, definition name
ab

Answer the following questions for the following.


 (3 marks) welcome.display() [PTA-6; July-'22]
1. Differentiate PYTHON and C++. Ans. Welcome → Module name
Ans.  [HY-2019; Aug-2021] · → Dot operator
ur

S. display() → Function call


PYTHON C++
No
5. What is sys.argv? What does it contain?
Python is typically C++ is typically a
.s

 [May-'22]
(i) an "interpreted" "compiled" language
language Ans. sys.argv is the list of command-line arguments
Python is a C++ is compiled passed to the Python program. argv contains
w

(ii) dynamic-typed statically typed all the items that come along via the command-
language language line input, it's basically an array holding the
Data type is not Data type is required command-line arguments of the program.
w

(iii) required while while declaring main(sys.argv[1]) :


declaring variable variable (i)  Accepts the program file (Python
program) and the input file (C++ file) as a
w

It can act both It is a general


as scripting and purpose language list(array).
(iv)
general purpose (ii)  argv[0] contains the Python program
language which is need not to be passed because
2. What are the applications of scripting by default _main_contains source code
language? [PTA-4; Sep-2020] reference.
Ans. (i) To automate certain tasks in a program (iii) argv[1] contains the name of the C++ file
(ii) Extracting information from a data set which is to be processed.

212
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


Part - IV the C++ file), which will be the argument
passed through main ().
Answer the following questions

Importing C++ Programs in Python


 (5 marks) (ii) Python's OS Module :
(i) The OS module in Python provides a
1. Write any 5 features of Python.
way of using operating system dependent
 [PTA-3; Mar-2020]
functionality.
Ans. (i) Python uses Automatic Garbage Collection.
(ii) The functions that the OS module allows
(ii) Python is a dynamically typed language.

m
you to interface with the Windows
(iii) Python runs through an interpreter. operating system where Python is running
(iv) Python code tends to be 5 to 10 times on.
shorter than that written in C++. os.system():

co
(v) In Python, there is no need to declare types (i) Execute the C++ compiling command (a
explicitly. string contains Unix, C command which
(vi) In Python, a function may accept an
also supports C++ command) in the shell
(Here it is Command Window).
argument of any type, and return multiple

.
(ii) For Example to compile C++ program g++
values without any kind of declaration

ks
compiler should be invoked.
beforehand.
(iv) Command : os.system (‘g++’ + <varaiable_
2. Explain each word of the following command name1> ‘-<mode>’ + <variable_name2>
 Python <filename.py> -<i> <C++ filename
(i) os.system:- function system() defined
without cpp extension> [May-'22]
oo
Ans. Python <filename.py> -i <C++ filename without
in os module to interact
with the operating system
cpp extension>
(ii) g++:- General compiler to
where,
compile C++ program
Python Keyword to execute the under Windows
ab

Python program from Operating system.


command-line (iii) variable_name1:- Name of the C++ file
filename.py Name of the Python along with its path and
program to executed with extension .cpp in
ur

string format.
-i input mode (iv) mode:- To specify input or output
C++ filename without Name of C++ file to be mode. Here it is o prefixed
cpp extension compiled and executed with hyphen.
.s

(v) variable_name2:- Name of the executable


3. What is the purpose of sys, os, getopt module
file with extension .exe in
in Python? Explain.
string format.
w

Ans. (i) Python's sys module : This module provides


access to built in variables used by the interpreter. Python getopt module :
One among the variable in sys module is argv. (i) The getopt module of Python helps you to
w

sys.argv : parse (split) command-line options and


(i) sys.argv is the list of command-line arguments arguments.
passed to the Python program. argv contains (ii) This module provides getopt() method to
w

all the items that come along via the command- enable command-line argument parsing.
line input, it's basically a list holding the (iii) Python getopt.getopt method :
(i) This method parses command-line options
command-line arguments of the program.
and parameter list. Following is the syntax
(ii) To use sys.argv, import sys should be
for this method −
used. The first argument, sys.argv[0]
(ii) <opts>,<args>=getopt.getopt(argv, options,
contains the name of the python program
(example pali.py) and sys.argv [1]is the next [long_options])
argument passed to the program (here it is ■  argv - This is the argument list

213
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit V - Chapter 14

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


of values to be parsed (splited).
In our program the complete
4.
 
Write the syntax for getopt() and explain its
arguments and return values. [PTA-2, 5]
command will be passed as a list. Ans. Python getopt Module :
For example: (i) The getopt module of Python helps you to
c:\pyprg\pali.py -i c:\pyprg\pali_cpp parse (split) command-line options and
■  options - This is string of option arguments.
letters that the Python program (ii) This module provides getopt() method to

m
recognize as, for input or for output, enable command-line argument parsing.
with options (like 'i' or 'o') that  getopt.getopt method : This method parses
command-line options and parameter list.
followed by a colon (:).
Following is the syntax for this method −

co
 Here colon is used to denote the <opts>,<args>=getopt.getopt(argv, options,
mode. [long_options])
■  long_options - This contains a list of Here is the detail of the parameters −
strings. Argument of Long options (i) argv : This is the argument list of values

.
should be followed by an equal sign to be parsed (splited). In our program the

ks
('='). complete command will be passed as a list.
■ In our program the C++ file name (ii) options : This is string of option letters that
along with its path will be passed as the Python program recognize as, for input
string and ‘i’ i will be also passed to or for output, with options (like ‘i’ or ‘o’)
oo
indicate it as the input file. that followed by a colon (:). Here colon is
(iv) getopt() method returns value consisting used to denote the mode.
of two elements. (iii) long_options : This contains a list of
(v) Each of these values are stored separately strings. Argument of Long options should
be followed by an equal sign ('='). In our
ab

in two different list (arrays) opts and args.


(vi) Opts contains list of splitted strings like program the C++ file name along with its
path will be passed as string and ‘i’ i will be
mode and path. args contains error string,
also passed to indicate it as the input file.
if at all the comment is given with wrong
path or mode.  getopt() method returns value consisting of
ur

two elements. Each of these values are stored


(vi) args will be an empty list if there is no error.
separately in two different list (arrays) opts and
(vii) Example : args. Opts contains list of splitted strings like
opts, args = getopt.getopt (argv, mode and path. args contains error string, if at
.s

"i:",['ifile=']) all the comment is given with wrong path or


■ where opts contains - ('i', 'c:\\pyprg\\ mode. args will be an empty list if there is no
p4')] error.
w

■ -i: - option mode should be followed


For example, The Python code which is going
by : (colon)
to execute the C++ file p4 in command line will
■ 'c:\\pyprg\\p4' - value absolute path have the getopt() method like the following one.
w

of C++ file.
(viii) In our examples since the entire command opts, args = getopt.getopt (argv, "i:",['ifile='])
line commands are parsed and no leftover where opts contains [('-i', 'c:\\pyprg\\p4')]
w

argument, the second argument args will


be empty []. -i :- option nothing but
(ix)  If args is displayed using print() command mode should be
it displays the output as []. followed by :
(x) Example : 'c:\\pyprg\\p4' value nothing but the
>>>print(args) absolute path of C++
file.
[]

214
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


I n our examples since the entire command line
commands are parsed and no leftover argument, Hands on Experience

Importing C++ Programs in Python


the second argument args will be empty []. 1. Write a C++ program to create a class called
If args is displayed using print() command it Student with the following details
displays the output as []. Protected member
Rno integer
5. Write a Python program to execute the
Public members

m
following c++ coding
void Readno(int); to accept roll number and
#include <iostream> assign to Rno
using namespace std; void Writeno(); To display Rno.

co
int main() The class Test is derived Publically from the
Student class contains the following details
{ cout<<“WELCOME”;
Protected member
return(0);
Mark1 float
}

.
Mark2 float
The above C++ program is saved in a file Public members

ks
welcome.cpp void Readmark(float, float); To accept mark1
Ans. #Now select File→New in Notepad and type the and mark2
Python program as main.py void Writemark(); To display the marks
Create a class called Sports with the following
oo
# Program that compiles and executes a .cpp file detail
# Python main.py -i welcome Protected members
import sys, os, getopt score integer
def main(argv): Public members
ab

cpp_file = '' void Readscore(int); To accept the score


void Writescore(); To display the score
exe_file = '' The class Result is derived Publically from Test
opts, args = getopt.getopt(argv, "i:",['ifile=']) and Sports class contains the following details
ur

for o, a in opts: Private member


if o in ("-i", "--ifile"): Total float
cpp_file = a + '.cpp' Public member
void display() assign the sum of mark1, mark2,
.s

exe_file = a + '.exe' score in total.


run(cpp_file, exe_file) invokeWriteno(), Writemark() and Writescore().
def run(cpp_file, exe_file): Display the total also.
w

print("Compiling " + cpp_file) Save the C++ program in a file called hybrid.
Write a python program to execute the
os.system('g++ ' + cpp_file + ' -o ' + exe_ file) hybrid.cpp
w

print("Running " + exe_file) Ans. In Notepad, type the C++ program.


print("-------------------------") #include<iostream>
print using namespace std;
w

os.system(exe_file) class student


{
print protected:
if __name__ =='__main__': int no;
main(sys.argv[1:]) public:
Output : void readno(int rollno)
{
WELCOME mo = rollno;
}

215
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or

Unit V - Chapter 14

Sura’s
Available at All Leading Bookstores

➠ XII Std - Computer Science


void writeno()
{
 
save this file as hybrid.cpp
Now type the python program in New Notepad
cout<<"\n Roll no."<<rno; file.
}}; #python hybrid.py -i hybrid.cpp
class test: public student import sys,os,getopt
{ def main(argv);
protected:
cpp_file="
float mark1,mar2;

m
public: exe_file="
void readmark(float m1, float m2) opts, args = getopt.getopt(argv, "i:",
{ [ifile='])

co
mark1 = m1; for o, a in opts:
mark2 = m2; if o, a in opts:
} cpp_file=a+'.cpp'
void writemark() exe_file=a+'.exe'
{ run(cpp_file, exe_file)

.
cout<<"\n mark1"<<mark1; def run(cpp_file, exe_file)

ks
cout<<"\n mark2"<<mark2;
print("Compiling"+cpp_file)
}};
class sports os.system('g++'+ cpp_file + '-o'+ exe_file)
{ print("Running" + exe_file)
protected: print("------------------")
int score;
oo print
public: os.system(exe_file)
void readscore(int s) print
{ if__name__=='__main__':
ab

score = s; main(sys.argv[1:])
} Output :
void writescore() Rollno : 5
{
Mark1 : 100
cout<<"SCORE:"<<score;
Mark2 : 100
ur

}};
class result : public test, public sports TOTAL MARKS : 200
{ SCORE : 200
private: 2. Write a C++ program to print boundary
.s

float total; elements of a matrix and name the file as


public;
Border.cpp. Write a python program to execute
void display()
the Border.cpp
w

{
total = mark1 + mark2; Ans. Select File → New in Notepad and type the C++
cout<<"TOTAL MARKS: "<<total; program.
}}; #include<iostream>
w

int main() #include<bits/stdc++.h>


{ using namespace std;
result r; const int MAX = 100;
w

r.readno(5); void printBoundary(int a[][max], int m, int n)


r.readmark(100,100); {
r.readscore(200); for(int i=0; i < m; i++)
r.writeno(); {
r.writemark(); for(int j=0; j < n; j++)
r.display(); {
r.writescore(); if(i= =0 || j= =0 || i= =n–1 ||
return ();  j= =n–1)
} cout<<a[i][j]<<" ";

216
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


else
PTA Questions and Answers

Importing C++ Programs in Python


cout <<" "
cout << " "; 1 MARK
}
cout <<"\n; 1. Which of the following is the special variable
}} which by default stores the name of the file?
 [PTA-1]

m
int main()
(a) __name__ (b) __init__
{
(c) __del__ (d) __def__
int a[4][MAX] = { {1,2,3,4}, {5,6,7,8},
 [Ans. (a) __name__]

co
 {1,2,3,4}, {5,6,7,8}};
print Boundary(a,4,4); 2. _______ is a built-in variable which evaluates
return 0; to the name of the current module. [PTA-4]
} (a) __name__ (b) __main__

.
save it as Border.cpp (c) __mode__ (d) __init__

ks
open a New notepad file and type the python  [Ans. (a) __name__]
program to execute border.cpp Government Exam Questions and Answers
#python border.py -i border.cpp oo
import sys,os,getopt 1 MARK
def main(argv):
1. Which of the following is not a scripting
cpp_file ="
exe_file =" language?  [Sep-2020]
(a) Ruby (b) DBMS
ab

opts, args= getopt.getopt(argv, "i:",


['ifile="]) (c) Perl (d) JavaScript
 [Ans. (b) DBMS]
for o, a in opts:
if o in("-i", "--ifile"): 2 MARK
ur

cpp_file = a+'.cpp' 1. Write the syntax of getopt.getopt method.


exe_file = a+'.exe'
 [May-'22]
run(cpp_file, exe_file)
Ans. <opts>,<args> = getopt.getopt(argv, options,
.s

def run(cpp_file, exe_file): [long_options]).


print("Compiling" + cpp_file)
os.system('g++'+ cpp_file + '-o'+ exe_file)
w

additional questions and Answers


print("Running" + exe_file)
print("---------------") Choose the Correct Answer 1 MARK
w

print
1. Which of the following are general purpose
os.system(exe_file)
programming language?
print (a) Python (b) C++
w

if__name__=='__main__': (c) Java (d) All of these


main(sys.argv[1:])  [Ans. (d) All of these]
Output :
1 2 3 4 2. Which of the following is not general purpose
5 8 language?
1 4 (a) Python (b) Perl
5 6 7 8 (c) Java (d) C++
 [Ans. (b) Perl]

217
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or


Available at All Leading Bookstores

Sura’s ➠ XII Std - Computer Science


19. The command to change to the folder where 27. How many options getopt provides to enable
Python is located is command line argument parsing?

Importing C++ Programs in Python


(a) Change (b) CD (a) 3 (b) 7 (c) 2 (d) 4
(c) Dir (d) CDir  [Ans. (c) 2]
 [Ans. (b) CD] 28. Getopt () method returns values are started in
(a) Opts (b) Args
20. The syntax to execute the python program is
(c) Sys (d) a and b

m
(a) Python –i <filename.Py> <C++ filename>
 [Ans. (d) a and b]
(b) Python <filename – py> <C++ filename> -i
29. The mode ‘i’/’o’ parses each values of the
(c) Python <C++ filename> -i <filename.py>

co
command line and pass as argument to the list
(d) Python <filename.py> -i <C++ filename> called
 [Ans. (d) Python <filename.py> -i <C++ (a) Args (b) Opts
filename>] (c) Sys (d) Argv

.
21. In the command python <filename.py> - i  [Ans. (b) Opts]

ks
<C++ filename> where i denotes. 30. Which of the following definition invoke the
(a) Information (b) Input mode ‘g++’ compiler and creates the exe file?
(c) ios (d) Interpreter (a) Main (b) Name
[Ans. (b) Input mode]
oo (c) Run (d) System
 [Ans. (c) Run]
22. Which of the following is not a python module? Match the following
(a) OS (b) Sys 1. 1 PHP Interface with C
(c) Tel (d) Getopt
ab

2 HTML Interface generator


 [Ans. (c) Tel] both C & C++
23. The operator used to access the python 3 SWIG Programming
functions using modules is language
ur

(a) . (b) : (c) , (d) : : 4 API Scripting language


 [Ans. (a) .] (a) 1-2-3-4 (b) 4-3-2-1
24. Which of the following is not a python module? (c) 4-2-3-1 (d) 4-1-2-3
.s

(a) Sys (b) OS  [Ans. (b) 4-3-2-1]


(c) Getopt (d) g++ Choose the odd man out
 [Ans. (d) g++]
w

1. (a) Java (b) Python


25. Which of the following is a python module? (c) HTML (d) C++[Ans. (b) Python]
(a) Sys (b) OS
Choose and fill in the blanks
w

(c) Getopt (d) All of these


 [Ans. (d) All of these] 1. ______ is typically interpreted language.
(a) Python (b) Java
w

26. Which of the following is an array holding the


command line arguments of the program? (c) C++ (d) None of these
(a) g++ (b) argv  [Ans. (a) Python]
(c) Opts (d) Getopt 2. ______ is mostly used as a ‘glue’ language.
 [Ans. (b) argv]
(a) C++ (b) Java
(c) Python (d) CSV
 [Ans. (c) Python]

219
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores

12th
STD
INSTANT SUPPLEMENTARY EXAM - JULY 2022
Reg. No.

COMPUTER SCIENCE (with Answers)


Time Allowed : 3.00 Hours] PART - III [M aximum Marks : 70

Instructions :

m
1) Check the question paper for fairness of printing. If there is any lack of fairness, inform the Hall
Supervisor immediately.
2) Use Blue or Black ink to write and underline and pencil to draw diagrams

co
PART - I
Note : (i) Answer all the questions. (15×1=15)
(ii) Choose the most appropriate answer from the given four alternatives and write the option code and
the corresponding answer.

.
ks
1. Which of the following is a unit of code that is 9. What will be result of the following Python code
often defined within a greater structure? S = [x**2 for x in range (5)]
(a) Subroutines (b) Function print (S)
(c) Files (d) Modules (a) [0, 1, 2, 4, 5] (b) [0, 1, 4, 9, 16]
2.
oo
Which of the following functions build the (c) [0, 1, 4, 9, 16, 25] (d) [1, 4, 9, 16, 25]
abstract data type? 10. Class members are accessed through which
(a) Constructors (b) Destructors operator?
(c) Recursive (d) Nested (a) & (b) . (c) # (d) %
11. A table is known as :
ab

3. Which scope refers to variables defined in


current function? (a) Tuple (b) Attribute
(c) Relation (d) Entity
(a) Local Scope (b) Global Scope
12. The command to delete a table is :
(c) Module Scope (d) Function Scope
(a) DROP (b) DELETE
ur

4. Which of the following shortcut is used to create (c) DELETE ALL (d) ALTER TABLE
new Python Program? 13. Which of the following mode is used when
(a) Ctrl + C (b) Ctrl + F dealing with non-text files like image or exe files?
(c) Ctrl + B (d) Ctrl + N (a) Text mode (b) Binary mode
.s

5. ________ is used to print more than one item (c) xls mode (d) CSV mode
on a single line. 14. getopt () will return an empty array if there is no
(a) Semicolon (;) (b) Dollar ($) error in splitting strings to :
w

(c) Comma (,) (d) Colon (:) (a) argv variable (b) opt variable
(c) args variable (d) ifile variable
6. Which is the most Comfortable loop?
15. The function that returns the largest value of the
w

(a) do..while (b) while


selected column is :
(c) for (d) if...elif
(a) MAX () (b) LARGE ()
7. Which of the following keyword is used to begin (c) HIGH () (d) MAXIMUM ()
w

the function block?


(a) define (b) for PART - II
Note : Answer any six questions. Question No. 24 is
(c) finally (d) def
compulsory. 6 × 2 = 12
8. What is Stride?
16. Differentiate constructor and selector.
(a) index value of slide operation
17. Write a short note on Namespaces.
(b) first argument of slice operation
18. Write note on range ( ) in loop.
(c) second argument of slice operation
19. What is meant by scope of variables? Mention
(d) third argument of slice operation its types.
[251]

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores

252 Sura’s  12th Std - Computer Science  Instant Supplementary Exam - July 2022 Question Paper with Answers

20. What is set in Python? 37. (a)  Write the different types of constraints and
21. Mention few examples of Database Management their functions?
System. (OR)
22. Differentiate compiler and interpreter. (b) Explain the characteristics of DBMS.
23. Which method is used to fetch all rows from the 38. (a)  Write the different methods to read a file in
database table? Python.
24. What will be the output of the following code? (OR)

m
Str1 = "School"
(b) What is the purpose of range ( )? Explain
print (str1*3) with an example.
PART - III 

co
Note : Answer any six questions. Question No. 33 is
compulsory. 6 × 3 = 18 ANSWER
25. Write the syntax of 'while' loop. PART - I
26. Write the basic rules for global keyword in 1. (b) Function

.
python. 2. (a) Constructors

ks
27. Identify the module, operator, definition name 3. (a) Local Scope
for the following: 4. (d) Ctrl + N
welcome.display() 5. (c) Comma (,)
28. Mention the difference between fetchone ( ) and 6. (c) for
fetchmany ( ).
oo 7. (d) def
29. Write a python program to modify an existing
file. 8. (d) third argument of slice operation
30. Write a SQL statement to modify the student 9. (b) [0, 1, 4, 9, 16]
table structure by adding a new field. 10. (b) .
ab

31. Write a note on open ( ) function of Python. What 11. (c) Relation
are the difference between its two methods? 12. (a) DROP
32. List the general types of data visualization. 13. (b) Binary mode
33. What is the output of the following program? 14. (c) args variable
ur

class Greeting :
def _ init _ (selt, name) : 15. (a) MAX ( )
self._ name = name PART - II
def display (self) :
16.
.s

print ("Good Morning", self._ name)


obj = Greeting ('Bindu Madhavan") S.
obj.display ( ) Constructors Selectors
No.
w

PART - IV
(i) Constructors are Selectors are
Note : Answer all the questions: 5 × 5 = 25 functions that functions that retrieve
34. (a) Discuss about linear search algorithm. build the abstract information from the
w

(OR) data type. data type.


(b) Explain the different types of function with (ii) Constructors Selectors extract
an example. create an object, individual pieces of
35. (a) What is nested tuple? Explain with an
w

bundling together information from the


example. different pieces of object
(OR) information.
(b) Explain about SQLite and the steps to be
17. Namespaces are containers for mapping names
used.
of variables to objects.
36. (a) Write a detail note on 'for' loop.
Example : a : = 5
(OR)
(b)  Explain the different types of operators used Here the variable 'a' is mapped to the value '5'.
in Python:

[email protected] Ph: 8124201000 / 8124301000


www.kalvinesan.com

You might also like