0% found this document useful (0 votes)
1K views262 pages

12th Std Computer Science MCQs

This chapter discusses functions in programming languages. Some key points: - A function is a block of code that performs a specific task. Functions allow for modularity and code reuse. - Functions have an interface that defines how they can be called (parameters, return type) and an implementation that contains the code. - Parameters are the variables passed into a function. Arguments are the actual values passed to parameters during a function call. - Functions should be pure and avoid side effects to make them reusable. Side effects include modifying external state or variables outside the function.
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)
1K views262 pages

12th Std Computer Science MCQs

This chapter discusses functions in programming languages. Some key points: - A function is a block of code that performs a specific task. Functions allow for modularity and code reuse. - Functions have an interface that defines how they can be called (parameters, return type) and an implementation that contains the code. - Parameters are the variables passed into a function. Arguments are the actual values passed to parameters during a function call. - Functions should be pure and avoid side effects to make them reusable. Side effects include modifying external state or variables outside the function.
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

This is only for Sample

for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

COMPUTER SCIENCE

m
co
E
12 Standard
th FREWorkbook
e
Practic with
anual
Lab M

s.
Based on the Updated New Textbook

Salient Features
ok
 Exhaustive Additional MCQs, VSA and SA question with answers are given in each chapter.
o
 All the objective type (1 Mark) questions are given with 4 options.
ab

(i) Choosing the correct option


(ii) Matching
(iii) Filling the blanks
ur

(iv) Choosing the Correct\Incorrect Statement.


(v) Picking the Odd one Out.
(vi) Assertion and Reason.
.s

 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)
and Half Yearly Exam - 2019 (HY-2019) are incorporated in the appropriate sections.
w

 Govt. Model Question Paper - 2019, Quarterly Exam - 2019 and Half Yearly Exam - 2019
Question Paper are given.
w

 Public Exam Question Paper March - 2020 Question Paper with answer are given.
w

SURA PUBLICATIONS
Chennai

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Contents

m
Chapter Page
Title

co
Unit
No No

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

s.
Solving
Techniques 3. Scoping 18-27
4. Algorithmic Strategies 28-43

ok
5. Python -Variables and Operators 44-59
UNIT- II 6. Control Structures 60-75
Core Python 7. Python functions 76-95
o
8. Strings and String manipulations 96-110
ab

UNIT-III 9. Lists, Tuples, Sets and Dictionary 111-133


Modularity and
OOPS 10. Python Classes and objects 134-145
ur

UNIT-IV 11. Database Concepts 146-163


Database 12. Structured Query Language (SQL) 164-185
concepts and
13.
.s

Python and CSV files 186-203


MySql
UNIT-V 14. Importing C++ programs in Python. 204-217
w

Integrating 15. Data manipulation through SQL 218-230


Python with 16. Data visualization using pyplot: line chart, pie chart 231-243
MySql and and bar chart
w

C++
Government Model Question Paper - 2019-20 244-246
w

Common Quarterly Examination - 2019 247-248


Common Half Yearly Examination - 2019 249-251
Public Exam Question Paper March - 2020 with Answers 252-260

iii

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

UNIT-I
 
PROBLEM SOLVING TECHNIQUES

1
Chapter
FUNCTION

m
co
CHAPTER SNAPSHOT
1.1 Introduction

s.
1.2 Function with respect to Programming language
1.2.1 Function Specification
1.2.2 Parameters (and arguments)

ok
1.3 Interface Vs Implementation
1.3.1 Characteristics of interface
1.4 Pure functions
1.4.1 Impure functions
o
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]
(a) Subroutines (b) Function
Part - I
ur

(c) Definition (d) Parameters


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

perform a particular task is called definition are called [HY-2019]


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

 [Ans. (a) Subroutines]  [Ans. (a) Arguments]


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

(a) Subroutines (b) Function  [PTA-4]


(c) Files (d) Modules (a) Curly braces (b) Parentheses
 [Ans. (b) Function] (c) Square brackets (d) indentations
w

3. Which of the following is a distinct syntactic  [Ans. (b) Parentheses]


block? [PTA-6] 7. Which of the following defines what an object
(a) Subroutines (b) Function can do?
(c) Definition (d) Modules (a) Operating System (b) Compiler
 [Ans. (c) Definition] (c) Interface (d) Interpreter
 [Ans. (c) Interface]
[1]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


8. Which of the following carries out the 5. Which of the following is a normal function
Unit I - Chapter 1

instructions defined in the interface? definition and which is recursive function


(a) Operating System (b) Compiler definition.
(c) Implementation (d) Interpreter i) let rec sum x y :
 [Ans. (c) Implementation] return x + y
ii) let disp :

m
9. The functions which will give exact result when print 'welcome'
same arguments are passed are called [PTA-3] iii) let rec sum num :
(a) Impure functions (b) Partial Functions if (num!=0) then return num + sum
(num-1)

co
(c) Dynamic Functions (d) Pure functions
 [Ans. (d) Pure functions] else
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

s.
(iii) Recursive function
(c) Dynamic Functions (d) Pure functions
 [Ans. (a) Impure function] Part - III
Part - II Answer the following questions

ok
Answer the following questions  (3 marks)
 (2 marks) 1. Mention the characteristics of Interface.
1. What is a subroutine? [PTA-1; HY-2019] Ans. (i) The class template specifies the interfaces to
enable an object to be created and operated
o
Ans. (i) Subroutines are the basic building blocks of
computer programs. Subroutines are small properly.
sections of code that are used to perform a (ii) An object's attributes and behaviour is
ab

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

Ans. (i) strlen is a pure function because the


Ans. A function is a unit of code that is often defined function takes one variable as a parameter,
within a greater code structure. Specifically, a and accesses it to find its length.
function contains a set of code that works on (ii) This function reads external memory but
does not change it, and the value returned
.s

many kinds of inputs, like variants, expressions


and produces a concrete output. derives from the external memory accessed.

3. Write the inference you get from X:=(78). 3. What is the side effect of impure function.
Give example.
w

[PTA-5]
Ans. X:= (78) has an expression in it but (78) is not
itself an expression. Rather, it is a function Ans. Impure Function has the following side effects
definition. Definitions bind values to names, in (i) Function impure (has side effect) is that it
doesn't take any arguments and it doesn't
w

this case the value 78 being bound to the name


‘X’. return any value.
(ii) Function depends on variables or functions
4. Differentiate interface and implementation.
outside of its definition block.
w

Ans. The difference between interface and


(iii) It never assure you that the function will
implementation is
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
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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
Answer the following questions

Function
the function definition.
(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

m
variable 'y'. on [PTA-2]
(i) Parameter without Type
4. Differentiate pure and impure function.
(ii) Parameter with Type
Ans.  [PTA-3, 6]

co
Ans. Parameters (and arguments) : Parameters
S. No. Pure Impure 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

s.
on its arguments not solely depend example of a function, definition :
passed. on its arguments (requires: b>=0 )
passed. (returns: a to the power of b)

ok
let rec pow a b:=
(ii) If you call the pure If you call the
if b=0 then 1
functions with impure functions
else a * pow a (b –1)
the same set of with the same set
■  In the above function definition variable
arguments, you will of arguments,
‘b’ is the parameter and the value which is
o
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, (data types). Some language compiler
solves this type (data type) inference
ur

random(), Date().
(iv) They do not modify They may modify problem algorithmically, but some require
the arguments the arguments the type to be mentioned.
which are passed to which are passed ■  In the above function definition if
.s

them to them expression can return 1 in the then branch,


by the typing rule the entire if expression
5. What happens if you modify a variable outside has type int.
the function? Give an example.
■ 
w

Since the if expression has 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. compared to 0 with the equality operator,
For example : so ‘b’ is also a type of ‘int’. Since ‘a’ is
w

let y: = 0 multiplied with another expression using


(int) inc (int) x the * operator, ‘a’ must be an int.
y: = y + x; (ii) Parameter with Type : Now let us write
w

the same function definition with types


return (y)
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
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


■ When we write the type annotations for (iv) The above function square is a pure function
because it will not give different results for
Unit I - Chapter 1

‘a’ and ‘b’ the parentheses are mandatory.


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
■ There are times we may want to explicitly that if a function is pure, then if it is called

m
several times with the same arguments,
write down types. This is useful on
the compiler only needs to actually call the
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;

co
Explicitly annotating the types can help
if i <strlen (s) then
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

s.
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
i) Name of the function to work out that strlen is a pure function
and that ‘s’ is not updated in the loop, then

ok
ii) Identify the statement which tells it is a
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)  Statement which invoke the function one time.
recursively (vii) From these what we can understand, strlen
o
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,
you can never be sure that the function
w

(ii) For example the mathematical function sin


(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
arguments, you will always get the same random() will give different outputs for the
w

result. same function call.


let Random number
(iii) A function can be a pure function provided
it should not have any external variable let a := random()
w

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
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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
the speed of the car he just presses the

Function
Ans. Interface :
accelerator to get the desired behaviour.
(i) An interface is a set of action that an object Here the accelerator is the interface
can do. For example when you press a light between the driver (the calling / invoking

m
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
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.

co
that a class must have in order to be a new It's where fuel, air, pressure, and electricity
interface. 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

s.
(). The purpose of interfaces is to allow the separate interface from implementation.
computer to enforce the properties of the
class of TYPE T (whatever the interface is) Hands on Practice
must have functions called X, Y, Z, etc.

ok
(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.
implementation of that interface (the code Ans. let min 3 x y z :=
that carries out the behaviour). An object if x < y then
o
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
that carries out the behaviour). PTA Questions and Answers
.s

 For example, let's take the example of


increasing a car’s speed.
1 MARK
1. A function definition which call itself : [PTA-1]
w

ENGINE (a) Pure function (b) Impure function


(c) Normal function
(d) Recursive function
 [Ans. (d) Recursive function]
w

getSpeed 3 MARKS

1. Write a function that finds the minimum of its


w

No
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
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


8. Which of the following is an instance created
Government Exam Questions and Answers
Unit I - Chapter 1

from the class?


2 MARKS (a) parameter (b) function
(c) subroutines (d) object
1. Define pure function. Give one example.
 [Ans. (d) object]
 [QY-2019]
9. Which of the following is an example of

m
Ans. let min 3 x y z :=
impure function?
if x < y then
if x < z then x else z (a) Strlen() (b) random()
else (c) sqrf() (d) pure()

co
if y < z then y else z  [Ans. (b) random()]
10. In which type of function the return type is
additional questions and Answers solely depends on its argument passed?
(a) pure (b) impure
Choose the Correct Answer 1 MARK (c) parameterized (d) monochromatize

s.
1. Which of the following are expressed using  [Ans. (a) pure]
statements of a programming language? 11. In which type of function the return type does
(a) Functions (b) Algorithm not solely depends on its argument passed?

ok
(c) Interface (d) Implementation (a) Pure (b) Parameterized
 [Ans. (b) Algorithm] (c) Impure (d) Monochromatize
2. What must the used when a bulk of statements
to be repeated for many number of times?  [Ans. (c) Impure]
(a) Algorithm (b) Program Match the following
o
(c) Subroutines (d) Parameters 1. Match the following function definitions with
 [Ans. (c) Subroutines] their terms.
let rec odd xy : =
ab

3. Which of the following contains a set a


code that works an many kinds of input and List I List II
produces a concrete output?
i) Keyword 1) Xy
(a) Function (b) Algorithm
(c) Arguments (d) Language ii) Recursion 2) Odd
ur

 [Ans. (a) Function] iii) Function name 3) Rec


4. Which of the following are the values which iv) Parameters 4) let
are passed to a function definition?
(a) Parameters (b) Algorithm (i) (ii) (iii) (iv)
(a) 4 3 2 1
.s

(c) Data types (d) Arguments


 [Ans. (d) Arguments] (b) 1 2 3 4
5. The function definition is introduced by the (c) 4 1 2 3
keyword (d) 1 4 2 3
w

(a) def (b) rec  [Ans. (a) (i)-4; (ii)-3; (iii)-2; (iv)-1]
(c) let (d) infer
[Ans. (c) let] Choose and fill in the blanks
w

6. The recursive function is defined using the 1. Subroutines are called as __________
keyword
(a) Algorithm (b) Interface
(a) let (b) let rec
(c) name (d) infer (c) Parameters (d) Functions
w

 [Ans. (b) let rec]  [Ans. (d) Functions]


7. Which of the following is a description of all 2. ___________ are the variables in a function
functions in object oriented programming definition.
language?
(a) Arguments (b) Parameters
(a) Implementation (b) parameter
(c) Identifiers (d) Operators
(c) Interface (d) Arugument
[Ans. (b) Parameters]
 [Ans. (c) Interface]
6
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Explicitly _____________ the types can help Very Short Answers 2 MARKS
with debugging.
1. Differentiate parameters and arguments.

Function
(a) defining (b) annotating
(c) informing (d) computing Ans. Parameters are the variables in a function
 [Ans. (b) annotating] definition and arguments are the values which
are passed to a function definition.

m
4. All functions are ___________ definitions.
(a) static (b) dynamic 2. Give an example of function definition
parameter without type.
(c) algorithmic (d) static
 [Ans. (a) static] Ans. (requires: b>=0 )

co
(returns: a to the power of b)
5. A __________ combines the external interface
with an implementation of the interface. let rec pow a b:=
(a) parameter without type if b=0 then 1
(b) class declaration else a * pow a (b-1)

s.
(c) function definition 3. Give an example of function definition
(d) parameter with type parameter with type.
 [Ans. (b) class declaration] Ans. (requires: b> 0 )

ok
6. In object oriented programs _______ are the (returns: a to the power of b )
interface
let rec pow (a: int) (b: int) : int :=
(a) Implementation (b) parameters
(c) Interface (d) Arguments if b=0 then 1
 [Ans. (c) Interface] else a * pow b (a-1)
o
7. In object oriented programs, how the object is 4. What is recursive function?
processed and executed is ______________. Ans. A function definition which call itself is called
ab

(a) Implementation (b) Interface recursive function.


(c) recursion (d) function 5. Give an example of pure function.
 [Ans. (a) Implementation] Ans. let square x
8. Stolen is an example _________function. return: x * x
ur

(a) user defined (b) impure let i: = 0;


(c) pure (d) recursive if i <strlen (s) then
 [Ans. (c) pure] -- Do something which doesn't affect s
++i
.s

9. Evaluation of ______ functions does not cause


any side effects to its output? 6. Give an example of impure function.
(a) Impure (b) pure Ans. let y: = 0
(c) Recursive (d) built-in (int) inc (int) x
w

 [Ans. (b) pure] y: = y + x;


return (y)
Choose the correct statement
w

1. (i) Algorithms are not expressed using


 7. Construct on algorithm that arranges
statements of a programming language. meetings between these two types so that they
(ii) An interface is a set of action that an object change their color to the third type. In the end,
all should display the same color.
can do
w

Ans. let rec monochromatize a b c :=


(iii) Implementation does not carries out the
instructions defined in the interface. if a > 0 then
(iv) Pure functions will give exact result. a, b, c := a-1, b-1, c+2
(a) i and iii (b) ii and iv else
a:=0, b:=0, c:= a + b + c
(c) iii and ii (d) i, ii and iv
return c
 [Ans. (a) i and iii]

7
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Short Answers 3 MARKS 2. Write an algorithm to check whether the
entered number is even or odd.
Unit I - Chapter 1

1. Explain the syntax of function definitions. Ans. (requires: x>= 0)


Ans. (i) The syntax to define functions is close to let rec even x :=
the mathematical usage: the definition is x=0 || odd (x-1)
return ‘even’

m
introduced by the keyword let, followed by
the name of the function and its arguments; (requires: x>= 0)
then the formula that computes the image let odd x :=
x<>0 && even (x-1)
of the argument is written after an = sign. If

co
return ‘odd’
you want to define a recursive function: use
“let rec” instead of “let”. 3. Write a short note an syntax for function types.
(ii) Syntax : The syntax for function Ans. The syntax for function types :
definitions: x→y
x1 → x2 → y

s.
let rec fn a1 a2 ... an := k
(iii) Here the ‘fn’ is a variable indicating an x1 → ... → xn → y
identifier being used as a function name. The  The ‘x’ and ‘y’ are variables indicating types.
The type x → y is the type of a function that gets
names ‘a1’ to ‘an’ are variables indicating

ok
an input of type ‘x’ and returns an output of type
the identifiers used as parameters. The
‘y’. Whereas x1 → x2 → y is a type of a function
keyword ‘rec’ is required if ‘fn’ is to be
that takes two inputs, the first input is of type
a recursive function; otherwise it may be
‘x1’ and the second input of type ‘x2’, and
omitted. returns an output of type ‘y’. Likewise x1 → …
o
→ xn → y has type ‘x’ as input of n arguments
and ‘y’ type as output.
ab


ur
.s
w
w
w

8
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

 
DATA ABSTRACTION
2
Chapter

m

co
CHAPTER SNAPSHOT

s.
2.1 Data Abstraction – Introduction
2.2 Abstract Data Types
2.3 Constructors and Selectors

ok
2.4 Representation of Abstract datatype using Rational numbers
2.5 Lists, Tuples
2.5.1 List
2.5.2 Tuple
2.6 Data Abstraction in Structure
o
ab

Evaluation 4. A sequence of immutable objects is called


(a) Built in (b) List
(c) Tuple (d) Derived data
Part - I  [Ans. (c) Tuple]
ur

Choose the best answer  (1 mark) 5. The data type whose representation is known
1. Which of the following functions that build the are called [PTA-2; QY-2019]
abstract data type ? (a) Built in datatype
.s

(a) Constructors (b) Destructors (b) Derived datatype


(c) Recursive (d) Nested (c) Concrete datatype
 [Ans. (a) Constructors] (d) Abstract datatype 
w

2. Which of the following functions that retrieve  [Ans. (c) Concrete datatype ]
information from the data type? 6. The data type whose representation is unknown
(a) Constructors (b) Selectors are called
w

(c) Recursive (d) Nested (a) Built in datatype (b) Derived datatype
 [Ans. (b) Selectors] (c) Concrete datatype (d) Abstract datatype 
 [Ans. (d) Abstract datatype]
w

3. The data structure which is a mutable ordered


sequence of elements is called 7. Which of the following is a compound structure?
(a) Built in (b) List (a) Pair (b) Triplet
(c) Tuple (d) Derived data (c) Single (d) Quadrat
 [Ans. (b) List]  [Ans. (a) Pair]

[9]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


8. Bundling two values together into one can be 4. What is a List? Give an example. [QY - 2019]
Unit I - Chapter 2

considered as [Govt. MQP - 2019; PTA-4] Ans. (i) 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

m
9. Which of the following allow to name the can be of any type and can even be another
various parts of a multi-item object? [PTA-6] list.
(a) Tuples (b) Lists Example : lst := [10, 20]

co
x, y := lst
(c) Classes (d) Quadrats
 [Ans. (c) Classes] 5. What is a Tuple? Give an example.
Ans. (i) A tuple is a comma-separated sequence of
10. Which of the following is constructed by values surrounded with parentheses. Tuple
placing expressions within square brackets?

s.
is similar to a list.
(a) Tuples (b) Lists (ii) The difference between the two is that you
(c) Classes (d) Quadrats cannot change the elements of a tuple once
 [Ans. (b) Lists] it is assigned whereas in a list, elements can

ok
be changed.
Part - II
(iii) Example : colour= ('red', 'blue', 'Green')
Answer the following questions
 (2 marks) Part - III
1. What is abstract data type? Answer the following questions
o
Ans. (i) Abstract Data type (ADT) is a type (or  (3 marks)
class) for objects whose behavior is defined
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
Abstract datetype
ur

2. Differentiate constructors and selectors. No. datatype


Ans.  [PTA-2, 3; QY-2019] (i) Concrete Abstract Datatypes
datatypes or (ADT's) offer
S. structures a high level
Constructors Selectors
.s

No. (CDT's) are direct view (and use)


(i) Constructors are Selectors are implementations of a concept
functions that functions of a relatively independent of its
build the abstract that retrieve simple concept. implementation.
w

data type. information from


the data type. (ii) A concrete data Abstract data type
type is a data the representation
(ii) Constructors Selectors extract type whose of a data type is
w

create an object, individual pieces of representation is unknown.


bundling together information from known.
different pieces of the object
information. 2. Which strategy is used for program designing?
w

Define that Strategy. [Govt. MQP-2019]


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

10
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


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

Data Abstraction
(b) Tuple
(a) N1=number() (c) Class
(b) accetnum(n1) (d) Tuple
(c) displaynum(n1)
(e) List

m
(d) eval(a/b)
(f) Class
(e) x,y= makeslope (m), makeslope(n)
Part - IV
(f) display()
Answer the following questions

co
Ans. (a) Constructors
(b) Selectors  (5 marks)
(c) Selectors
(d) Selectors 1. How will you facilitate data abstraction.
(e) Constructors Explain it with suitable example. [PTA-2, 4]

s.
(f) Selectors Ans. Data abstraction is supported by defining an
abstract data type (ADT), which is a collection
4. What are the different ways to access the of constructors and selectors. To facilitate data
elements of a list. Give example.

ok
abstraction, you will need to create two types of
Ans. (i) The elements of a list can be accessed in functions: Constructors, Selectors
two ways. The first way is via our familiar Constructors :
method of multiple assignment, which
(i) Constructors are functions that build the
unpacks a list into its elements and binds
abstract data type.
o
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,
(iii) A second method for accessing the and its latitude and longitude.
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
constructor which creates the object city.
.s

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.
lst[0]
w

10 make city ( )
lst[1]
20
w

5. Identify Which of the following are List, Tuple city


and class ?
lat lon
(a) arr [1, 2, 34]
w

(b) arr (1, 2, 34) Constructor


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

11
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iii) To extract the information of a city object, Pair :
Unit I - Chapter 2

you would used functions like (vi) 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

m
functions extract the information of the 3. How will you access the multi-item? Explain
city object. with example.
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

co
getname ( ) getlat ( ) getlon ( ) represent multi-part objects where each
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]

s.
creation( )
Ans. List :
firstName := " "
(i) List is constructed by placing expressions
within square brackets separated by lastName := " "

ok
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. represented as
Example for List is [10, 20].
o
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

method of multiple assignment, which creation ( )


function belonging to the new datatype

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

(iii) In the above example x will become10 and datatype


id
y will become 20. A second method for
accessing the elements in a list is by the email
element selection operator, also expressed
.s

using square brackets. Let main() contains


(iv) Unlike a list literal, a square-brackets p1:=Person() statement creates
expression directly following another the object
w

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
lst[0] lastName :="Baskar" setting a field called
w

10 lastName with value


lst[1] Baskar
20 id :="994–222–1234" setting a field called
w

(v) In both the example mentioned above


id value 994–222–
1234
mathematically we can represent list similar
to a set. email="compsci@gamil.com" 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
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(ii) The class (structure) construct defines the 2. Which of the following provides modularity?
form for multi-part objects that represent a (a) Datatypes (b) Subroutines

Data Abstraction
person. (c) Classes (d) Abstraction
(iii) Person is referred to as a class or a type,  [Ans. (d) Abstraction]
while p1 is referred to as an object or an
instance. 3. Which of the following is a type for objects

m
whose behavior is defined by a set of value and
(iv) Here class Person as a cookie cutter, and
p1 as a particular cookie. Using the cookie a set of operations?
cutter you can make many cookies. Same (a) User-defined datatype
way using class created many objects of that (b) Derived datatype

co
type. (c) Built-in datatype (d) Abstract datatype
(v) A class defines a data abstraction by [Ans. (d) Abstract datatype]
grouping related data items. A class is not
just data, it has functions defined within it. 4. ADT behavior is defined by
We say such functions are subordinate to

s.
(i) Set of Variables (ii) Set of Value
the class because their job is to do things (iii) Set of Functions (iv) Set of Operations
with the data of the class.
(a) i, ii (b) ii, iii
Questions and Answers

ok
PTA (c) ii, iv (d) i, iii
 [Ans. (c) ii, iv]
1 MARK
5. The process of providing only the essentials
1. Expansion of ADT : [PTA-1] and hiding the details is known as
(a) Abstract Data Tuple
o
(a) Functions (b) Abstraction
(b) All Data Template (c) Encapsulation (d) Pairs
(c) Abstract Data Type  [Ans. (b) Abstraction]
ab

(d) Application Data Type


 [Ans. (c) Abstract Data Type] 6. Which of the following gives an implementation
independent view?
2. ADT can be implemented using ____. [PTA-5] (a) Abstract (b) Concrete
(a) singly linked list (b) doubly linked list (c) Datatype
ur

(c) either A or B (d) neither A nor B (d) Behavior of an object


 [Ans. (a) singly linked list]  [Ans. (a) Abstract]
Government Exam Questions and Answers 7. How many ways to implement an ADT?
.s

(a) Only one (b) Two


1 MARK (c) Three (d) Many
1. The datatype whose representation is unknown  [Ans. (d) Many]
w

is called [HY-2019] 8. Which of the following are implemented using


(a) Built-in datatype (b) Derived datatype & lists?
(c) Concrete datatype (d) Abstract datatype (a) Singly linked list ADT
w

 [Ans. (d) Abstract datatype]


(b) Doubly Linked list ADT
additional questions and Answers (c) Stack ADT (d) Queue ADT
w

Choose the Correct Answer 1 MARK (e) All of these [Ans. (e) All of these]
1. Which of the following is a powerful concept 9. Which of the following replicate how we think
that allows programmers to treat codes as about the world?
objects? (a) Queue ADT (b) Data Hiding
(a) Encapsulation (b) Data Abstraction (c) Data Abstraction (d) Stack ADT
(c) Inheritance (d) Polymorphism
[Ans. (c) Data Abstraction]
 [Ans. (b) Data Abstraction]
13
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. To facilitate data abstraction, How many types 19. l : = [10, 20] is an example
Unit I - Chapter 2

of functions are created? (a) Tuple (b) Set


(a) 2 (b) 3 (c) List (d) Dictionary
(c) 4 (d) Only one  [Ans. (c) List]
 [Ans. (a) 2] 20. List can also be called as
(a) Functions (b) Class

m
11. Which of the following function that facilitate
(c) Structure (d) Pairs
the data abstraction?
 [Ans. (d) Pairs]
(a) Constructors (b) Destructors 21. How many ways are there to represent pair

co
(c) Selectors (d) a and c datatype?
 [Ans. (d) a and c] (a) 2 (b) 4 (c) 3 (d) 5
12. Which of the following are functions that  [Ans. (a) 2]
22. Color = (‘red’, ‘green’, ‘blue’) is an example of
build the abstract datatype?
(a) Dictionary (b) List

s.
(a) Constructors (b) Destructors (c) Set (d) Tuple
(c) Selectors (d) All of these  [Ans. (d) Tuple]
 [Ans. (a) Constructors] 23. Which of the following does not allow us to

ok
13. Which of the following extract the information name the various parts of a multi-item object?
of the object? (a) List (b) Tuple
(c) Pair (d) All of these
(a) Constructors (b) Functions
 [Ans. (d) All of these]
(c) Selectors (d) Destructors
24. Which of the following defines a data
o
 [Ans. (c) Selectors]
abstraction by grouping related data items?
14. In which data representation, a definition for (a) List (b) Pair
each function is known.
ab

(c) Class (d) Tuple


(a) User defined (b) Buil-in  [Ans. (c) Class]
(c) Abstract (d) Concrete 25. Which of the following as bundled data and
 [Ans. (d) Concrete] the functions that work on that data?
15. How many parts are there in the program? (a) Object (b) Pair
ur

(a) 2 (b) 3 (c) List (d) Class


(c) 4 (d) Many  [Ans. (d) Class]
 [Ans. (a) 2] 26. CDT expansion is
(a) Collective Data Type (b) Class Data Type
.s

16. To implement the concrete level of data


abstraction the language python provides a (c) Concrete Data Type
compound structure called (d) Central Data Type
 [Ans. (b) Class Data Type]
(a) ADT (b) Concrete data
w

Match the following


(c) Pair
(d) User defined function [Ans. (c) Pair] 1. List I List II
17. Which of the following is contracted by placing i) List 1) arr (1,2,3,4)
w

expressions within square brackets separated ii) Tuples 2) getname (city)


by commas? iii) Class 3) Student [rno, name, mark]
(a) List (b) Tuple iv) Selectors 4) arr [1,2,3,4]
w

(c) Set (d) Dictionary


(i) (ii) (iii) (iv)
 [Ans. (a) List]
(a) 1 2 3 4
18. How many values can be stared in the list? (b) 4 3 2 1
(a) 4 (b) 10 (c) 4 3 2 1
(c) 100 (d) Multiple (d) 3 2 4 1
 [Ans. (d) Multiple]  [Ans. (c) (i)-4; (ii)-3; (iii)-2; (iv)-1]

14
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose the odd man out 8. ______ is made up of list or Tuples.
1. (a) List (a) Set (b) Pair

Data Abstraction
(b) Multiple assignment (c) Dictionary
(c) Classes (d) Control Structures [Ans. (b) Pair]
9. List is constructed by using ____ and ____.
(d) Element selection operator
(a) (), , (b) <>, ;

m
 [Ans. (c) Classes]
(c) [], , (d) [], :
Choose and fill in the blanks  [Ans. (c) [], ,]
1. Data Abstraction allows programmers to treat 10. A ____ is a comma separated values surround

co
code as _______. with parentheses.
(a) Objects (b) Classes (a) List (b) Tuple
(c) Members (d) Parameters (c) Set (d) Dictionary
 [Ans. (a) Objects]  [Ans. (b) Tuple]
11. Tuple is constructed by using ___ and __

s.
2. _______ are the representation for Abstract
(a) (), (b) [], (c) [],: (d) (),:
Data types.
 [Ans. (a) (),]
(a) Objects (b) Classes
12. A ____ is not just data, it has functions defined

ok
(c) Functions (d) Lists
within it.
 [Ans. (b) Classes] (a) Class (b) List
3. Classes are the representation for ____
(c) Pair (d) Object
(a) Abstract datatype  [Ans. (a) Class]
(b) Built-in datatype
o
Choose the incorrect statement
(c) Concrete datatype
1. (i) ADT is defined by set of values and set of
(d) Essential datatype
ab

operations
 [Ans. (a) Abstract datatype] (ii) ADT does specify how data will be organized
4. The ________ can be implemented using in the memory.
singly linked list or doubly linked list. (iii) Constructors are not used to built abstract
data type.
(a) Tuple ADT (b) List ADT
ur

(iv) Selectors are functions that retrieve


(c) Function ADT (d) List ADT information from the data type.
 [Ans. (b) List ADT] (a) i, ii (b) ii, iv
(c) ii, iii (d) i, iii, iv
.s

5. The basic idea of ____ is to structure programs  [Ans. (c) ii, iii]
so that they operate on abstract dat(a)
(a) Encapsulation (b) Polymorphism
Choose the incorrect pair
(c) Data type (d) Data Abstraction 1. (a) Abstraction – hiding the details
w

(b) Abstract data type–constructor & destructor


 [Ans. (d) Data Abstraction]
(c) Abstraction – providing only the essentials
6. A ______ data representation is defined as an (d) Abstract data type – constructor & selectors
w

independent part of the program. [Ans. (b) Abstract data type – Constructor &
(a) Abstract (b) Concrete destructor]
(c) List (d) Tuple Very Short Answers 2 MARKS
w

 [Ans. (b) Concrete]


1. Give an example of implementing an ADT.
7. _______ are functions that retrieve Ans. (i) There can be different ways to implement
information from the data type. an ADT, for example, the List ADT can
(a) Constructors (b) Selectors be implemented using singly linked list or
(c) List (d) Tuples doubly linked list.
 [Ans. (b) Selectors] (i) Similarly, stack ADT and Queue ADT can
be implemented using lists.
15
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Identify which is the constructor and selector 9. How the elements of a list can be accessed?
Unit I - Chapter 2

from the following statement. Ans. (i) The elements of a list can be accessed in two
(i)  The Functions that retrieve information ways.
from the datatype (ii) The first way is via multiple assignment
(ii) The function which creates an object. and the second method is by the element
Ans. (i) Selector selection operator.

m
(ii) Constructor
3. Write the pseudo code for the representation Short Answers 3 MARKS
of the rational number. 1. Identify the constructor and selector from the

co
Ans. The pseudo code for the representation of the
following.
rational number
(i) City = Make city (name, lat, lon)
x,y:=8,3
(ii) Get name (city)
rational(n,d)
(iii) Make point (x,y)
numer(x)/numer(y)
(iv) x coord (point)

s.
- - output :
(v) y coord (point)
4. How the concrete level of data abstraction Ans. (i) Constructor
implemented? (ii) Selector

ok
Ans. (i) To implement the concrete level of data (iii) Constructor
abstraction, languages like Python provides
(iv) Selector
a compound structure called Pair which is
made up of list or Tuple. (v) Selector
(ii) The first way to implement pairs is with the 2. Write a note on Data Abstraction.
o
List construct. Ans. (i) Data abstraction is supported by defining
an abstract data type (ADT), which is a
5. Write a note on pair datatype.
collection of constructors and selectors.
ab

Ans. (i) A pair is a compound data type that holds


(ii) Constructors create an object, bundling
two other pieces of data. The two ways of together different pieces of information,
representing the pair data type. while selectors extract individual pieces of
(ii) The first way is using List construct and the
information from the object.
second way to implement pairs is with the
ur

tuple construct. 3. Give an example of an ADT for rational


numbers.
6. Write a pseudocode to depressant rational
Ans. An ADT for rational numbers :
numbers using list.
Ans. rational(n, d):
- - constructor
.s

return [n, d] - - constructs a rational number with numerator


numer(x):  n, denominator d
return x[0] rational(n, d)
w

denom(x): - - selector
return x[1] numer(x) → returns the numerator of rational
 number x
7. How a class defines a data abstraction?
denom(y) → returns the denominator of rational
w

Ans. (i) A class defines a data abstraction by


 number y
grouping related data items. A class is not
just data, it has functions defined within it. Long Answers 5 MARKS
w

(ii) Functions are subordinate to the class


1. Explain the representation of Abstract
because their job is to do things with the
data of the class. datatype using rational numbers.
Ans. (i) The basic idea of data abstraction is to
8. From the statement P1 : = Preson(), What does structure programs so that they operate on
P1 and person referred. abstract data. That is, our programs should
Ans. Person is referred to as a class or a type, while p1 use data in such a way, as to make as few
is referred to as an object or an instance. assumptions about the data as possible.

16
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(ii) At the same time, a concrete data (vi) where both the <numerator> and
representation is defined as an independent <denominator> are placeholders for

Data Abstraction
part of the program. integer values. Both parts are needed
to exactly characterize the value of the
(iii) Any program consist of two parts. The
rational number. Actually dividing integers
two parts of a program are, the part that produces a float approximation, losing the

m
operates on abstract data and the part exact precision of integers.
that defines a concrete representation, is (vii) However, you can create an exact
connected by a small set of functions that representation for rational numbers by

co
implement abstract data in terms of the combining together the numerator and
concrete representation. denominator.
(iv) To illustrate this technique, let us consider (viii)
As we know from using functional
an example to design a set of functions for abstractions, we can start programming
manipulating rational numbers. productively before you have an

s.
implementation of some parts of our
(v) Example : A rational number is a ratio of program.
integers, and rational numbers constitute (ix) Let us begin by assuming that you already

ok
an important sub-class of real numbers. have a way of constructing a rational number
A rational number such as 8/3 or 19/23 is from a numerator and a denominator. You
typically written as : also assume that, given a rational number,
<numerator>/<denominator> you have a way of selecting its numerator
and its denominator component.
o
ab


ur
.s
w
w
w

17
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

  
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

 
SCOPING
3
Chapter

m
CHAPTER SNAPSHOT

co
3.1 Introduction 3.5 Module
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.5.3. Access Control

s.
3.4.1. Local Scope
3.4.2. Global Scope
3.4.3. Enclosed Scope

ok
3.4.4. Built-in-Scope

Evaluation 5. Which scope refers to variables defined in


current function?
(a) Local Scope (b) Global scope
o
Part - I (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 6. The process of subdividing a computer
of variables in one part of a program to program into separate sub-programs is called
another part of the same program. (a) Procedural Programming
(a) Scope (b) Memory (b) Modular programming
ur

(c) Address (d) Accessibility (c) Event Driven Programming


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

an object is called
7. Which of the following security technique
(a) Scope (b) Mapping
that regulates who can use resources in a
(c) late binding (d) early binding computing environment?
[Ans. (b) Mapping]
w

(a) Password (b) Authentication


3. Which of the following is used in (c) Access control (d) Certification
programming languages to map the variable [Ans. (c) Access control]
w

and object? [PTA-2; HY-2019]


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

(b) Protected members


4. Containers for mapping names of variables
(c) Secured members
to objects is called [QY-2019]
(d) Private members
(a) Scope (b) Mapping
(c) Binding (d) Namespaces [Ans. (d) Private members]
[Ans. (d) Namespaces]
[18]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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
double underscore to emulate the behaviour of
(c) Secured members
protected and private access specifiers.

m
(d) Private members
Part - III
[Ans. (a) Public members]
Answer the following questions
10. The members that are accessible from within

co
the class and are also available to its sub-classes
 (3 marks)
is called [PTA-6] 1. Define Local scope with an example.
(a) Public members Ans. (i) Local scope refers to variables defined in
(b) Protected members current function. Always, a function will

s.
first look up for a variable name in its local
(c) Secured members
scope.
(d) Private members
(ii) Only if it does not find it there, the outer

ok
[Ans. (b) Protected members] scopes are checked.
Part - II (iii) Look at this example :
Answer the following questions 1. Disp(): Entire program Output
 (2 marks) 2. a:=7 of the
o
3. print a Disp( ): Program
1. What is a scope? a:=7
4. Disp() print a 7
Ans. Scope refers to the visibility of variables,
ab

Disp ( )
parameters and functions in one part of a
program to another part of the same program.
(iv) On execution of the above code the variable
2. Why scope should be used for variable. State
a displays the value 7, because it is defined
the reason.
ur

and available in the local scope.


Ans. Essentially, variables are addresses (references,
or pointers), to an object in memory. When you 2. Define Global scope with an example. [PTA-6]
assign a variable with := to an instance (object), Ans. (i) A variable which is declared outside of all
.s

you're binding (or mapping) the variable to that the functions in a program is known as
instance. Multiple variable can be mapped to the Global variable.
same instance. (ii) This means, global variable can be accessed
w

inside or outside of all the functions in a


3. What is Mapping? [PTA-5]
program. Consider the following example
Ans. The process of binding a variable name with an
1. a:=10 Entire program Output
object is called mapping.= (equal to sign) is used
w

2. Disp(): a:=10 of the


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

4. What do you mean by Namespaces? 5. Disp() Disp 1( ):


print a
 [Govt. MQP-2019; PTA-4] 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
Here the variable 'a' is mapped to the value '5'. Disp() and then it displays 10, because a is
defined in global scope.
19
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Define Enclosed scope with an example. Ans. Output :

Unit I - Chapter 3

[PTA-3] 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.

m
Variables Scope
(ii) A variable which is declared inside a
function which contains another function Color:=Red Global
definition with in it, the inner function

co
b:=Blue Enclosed
can also access the variable of the outer
function. This scope is called enclosed G:=Green Local
scope.
Part - IV
(iii) When a compiler or interpreter search for a
Answer the following questions

s.
variable in a program, it first search Local,
and then search Enclosing scopes. Consider  (5 marks)
the following example

ok
1. Disp(): Entire program Output 1. Explain the types of scopes for variable or
2. a:=10 of the LEGB rule with example. [PTA-1]
Disp( )
3. Disp1(): a:=10 Program Ans. Types of Variable Scope :
Disp 1( ):
4. print a print a 10 There are 4 types of Variable Scope, let's discuss
5. Disp1() 10 them one by one:
o
Disp 1( ):
print a
6. print a Disp( )
Local Scope :
7. Disp() (i) Local scope refers to variables defined in
ab

current function. Always, a function will


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

Look at this example


resources in a computing environment.
(ii) It is a fundamental concept in security that 1. Disp(): Entire program Output
minimizes risk to the object. 2. a:=7 of the
3. print a Disp( ): Program
(iii) In other words access control is a selective
.s

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

through access modifiers.


w

5. Identify the scope of the variables in the


(ii) On execution of the above code the variable
following pseudo code and write its output
a displays the value 7, because it is defined
color:= Red
and available in the local scope.
w

mycolor():
b:=Blue Global Scope:
lue (i) A variable which is declared outside of all
w

myfavcolor(): the functions in a program is known as


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

20
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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

Scoping
3. a:=7 Disp( ) Program with the software
a:=7
Disp( )
4. print a print a 7
Disp 1( ):
5. Disp() Disp 1( ): 10 print a

m
print a
6. print a Disp 1( ):
print a
(iii) On execution of the above code the variable Disp( )
'a' which is defined inside the function

co
displays the value 7 for the function call LEGB rule :
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

s.
(i) All programming languages permit below in terms of hierarchy (highest to
functions to be nested. A function (method) lowest).
with in another function is called nested
Local(L) Defined inside function/
function.

ok
class
(ii) A variable which is declared inside a
Enclosed(E) Defined inside enclosing
function which contains another function
functions (Nested
definition with in it, the inner function
function concept)
can also access the variable of the outer
o
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
1. Disp(): Entire program Output GLOBAL
ur

2. a:=10 of the ENCLOSED


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

Disp 1( ):
5. Disp1() print a 10

6. print a Disp( )

2. Write any Five Characteristics of Modules.


7. Disp()
w

 [PTA-4, 6; HY-2019]
(iv) In the above example Disp1() is defined
Ans. The following are the desirable characteristics of
with in Disp(). The variable ‘a’ defined in
a module.
Disp() can be even used by Disp1() because
w

it is also a member of Disp(). (i) Modules contain instructions, processing


logic, and data.
Built-in Scope :
(ii) Modules can be separately compiled and
(i) The built-in scope has all the names that are
w

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 module which is defined (iv) Module segments can be used by invoking
in the library functions of a programming a name and some parameters.
language has Built-in or module scope. (v) Module segments can be used by other
Consider the following example. modules.

21
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Write any five benefits in using modular sum2()
programming.
Unit I - Chapter 3

[Govt. MQP-2019] 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

m
code many times. sum()
(iii) Programs can be designed more easily Print num 1
because a small team deals with only a
small part of the entire code. PTA Questions and Answers

co
(iv) Modular programming allows many
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 :

s.
 [PTA-1]
(vi) Code is short, simple and easy to
(a) Local (b) Global
understand.
(c) Enclosed (d) Built-in
(vii) Errors can easily be identified, as they are

ok
 [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. (a) Built-in scope variables
(ix) The scoping of variables can easily be (b) Enclosed scope variables
o
controlled. (c) Global scope variables
(d) Local scope variables
Hands on Practice  [Ans. (a) Built-in scope variables]
ab

3. Which of the following is not the example of


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

(c) class (d) functions


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

num1:=num1 + 10 1. What are modules?  [PTA-4]


Ans. A module is a part of a program. Programs
sum2( ) are composed of one or more independently
w

num1: = num1 + 10
developed modules.
sum2( )
Government Exam Questions and Answers
w

sum1( )
1 MARK
num1:=10 1. The kind of scope of the variable 'a' used in the
w

sum( ) pseudo code given below. [Govt. MQP-2019]


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

22
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. The SQL command to make a database as 6. The order in which variables have to be
current active database is [Govt. MQP-2019] mapped to the object in order to obtain the
value is called

Scoping
(a) CURRENT (b) USE
(c) DATABASE (d) NEW (a) Rule (b) Syntax
[Ans. (b) USE] (c) Scope (d) Hierarchy

m
 [Ans. (c) Scope]
2 MARKS
7. Which of the following rule is used to decide
1. What is LEGB rule? [QY-2019]
the order in which the scopes are to be searched
Ans. Scope also defines the order in which variables

co
for scope resolution?
have to be mapped to the object in order to
(a) LEGB (b) LGEB
obtain the value.
(c) LBEG (d) LGBE
additional questions and Answers  [Ans. (a) LEGB]

s.
8. Write the below interns of hierarchy (highest
Choose the Correct Answer 1 MARK to lowest)?
1. The part of a program that can see or use the (1) Reversed names in built in functions

ok
variables are called (2) Defined inside function
(a) Scope (b) Parameter (3) Defined inside enclosing function
(c) Function (d) Indentation (4) Defined at the uppermost level
[Ans. (a) Scope] (a) 3, 2, 1, 4 (b) 1, 4, 2, 3
(c) 2, 3, 1, 4 (d) 2, 3, 4, 1
o
2. Which of the following refers to the addresses [Ans. (d) 2, 3, 4, 1]
to an object in memory?
ab

(a) Functions (b) Indentation 9. How many types of variable scope are there?
(c) Variables (d) Operators (a)
2 (b) 4 (c) 3 (d) 6
 [Ans. (b) Indentation]  [Ans. (b) 4]

3. How many variables can be mapped to the 10. Which of the following is not a variable scope?
ur

same instance? (a) Global (b) Enclosed


(c) List (d) Built-in
(a) 2 (b) 3
 [Ans. (c) List]
(c) 4 (d) Multiple
.s

 [Ans. (d) Multiple] 11. Choose the type of scope for a variable ‘a’
defined in the following program.
4. Which of the following keeps track of all these Disp () :
w

mappings with namespaces? a:=7


(a) Programming languages Print a
(b) Application software Disp ()
w

(a) Global (b) Enclosed


(c) System software
(c) Local (d) Built-in
(d) My SQL
 [Ans. (c) Local]
 [Ans. (a) Programming languages]
w

12. A variable which is declared outside all the


5. How the names are mapped with objects in functions in a program is known as
programming language?
(a) Local (b) Enclosed
(a) name == object (b) name :: object
(c) Extern (d) Global
(c) name := object (d) object := name
[Ans. (d) Global]
[Ans. (c) name := object]

23
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


13. Which of the following variable can be 20. Which of the following members of a class are
accessed inside or outside of all the functions denied access from outside the class?
Unit I - Chapter 3

in a program? (a) Private (b) Protected


(a) Local (b) Global (c) Public (d) Enclosed
(c) Enclosed (d) Built-in
 [Ans. (b) Global]  [Ans. (a) Private]

m
21. Which of the following is not a classical object
14. What is the output of the statement in the oriented language?
following program?
(a) C++ (b) Java

co
X : = 10
Disp () : (c) Python (d) C[Ans. (d) C]
a:=7 22. Which of the following keywords are not used
print a to control the access to class members?
Displ () : (a) Public (b) Protected

s.
Print a (c) Public (d) Global
(a) 710 (b) 107 (c) 7 (d) 10
 [Ans. (d) Global]
 [Ans. (d) 10]

ok
23. How many access control keywords are there?
15. Which of the following can ease the job of
(a)
2 (b) 3 (c) 4 (d) 6
programming and debugging the program?
(a) Statements (b) Interaction  [Ans. (b) 3]
(c) Modules (d) Scopes 24. Find the odd man out
o
 [Ans. (c) Modules] (a) Public (b) Local
16. Which of the following programming enables (c) Protected (d) Private
ab

programmers to divide up the work and retry  [Ans. (b) Local]


pieces of the program independently? 25. The arrangement of private instance variables
and public methods ensures the principle of
(a) Modular Programming
(a) Inheritance (b) Polymorphism
ur

(b) Procedural Programming


(c) Encapsulation (d) Abstraction
(c) Object Oriented Programming
[Ans. (c) Encapsulation]
(d) Structural Programming
[Ans. (a) Modular Programming] 26. Which of the following members of a class are
.s

accessible from within the class and available


17. The example of modules are to its subclass?
(a) Procedures (b) Subroutines (a) Private (b) Protected
(c) Functions (d) All of these
w

(c) Public (d) All of these


 [Ans. (d) All of these]
 [Ans. (b) Protected]
18. Which of the following contain instructions, 27. By default, the Python. class members are
w

processing logic and data?


(a) Private (b) Protected
(a) Scopes (b) Modules
(c) Indentation (d) Access control (c) Global (d) Public
w

 [Ans. (b) Modules]  [Ans. (d) Public]


28. By default, the C++ and Java class members
19. The following are the type of variable scopes
are
Find the odd one out
(a) Local (b) Enclosed (a) Private (b) Protected
(c) Global (d) Protected (c) Public (d) Local
 [Ans. (d) Protected]  [Ans. (a) Private]

24
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


29. Programs are composed of one or more 6. _________ can be separately compiled and
independently developed stored in a library.

Scoping
(a) Access control (b) Encapsulation (a) Characteristics (b) Syntax
(c) Modules (c) Modules (d) none of these
(d) Members of a class [Ans. (c) Modules]  [Ans. (c) Modules]
Match the following

m
7. In Object Oriented Programming Language
1. List I List II security is implanted through ______
i) Scope 1) Mapping names (a) Access modifiers (b) Access modules

co
ii) Name spaces 2) Visibility of variables (c) Access variables (d) Keywords
iii) Module 3) Security technique  [Ans. (a) Access modifiers]
iv) Access 4) Sub dividing program 8. ________ is a selective restriction of access to
control data in a program?

s.
(i) (ii) (iii) (iv) (a) Control variable
(a) 2 1 4 3 (b) System authentication
(b) 3 1 4 2 (c) Access control (d) Modules

ok
(c) 2 4 1 3  [Ans. (c) Access control]
(d) 3 2 4 1
 [Ans. (a) (i)-2; (ii)-1; (iii)-4; (iv)-3] 9. __________ members of the class are accessible
from outside the class.
Choose and fill in the blanks
(a) Private (b) Protected
o
1. Scope refers to the visibility of ______
(c) Public (d) All of these
(a) Variables (b) Parameters
 [Ans. (c) Public]
(c) Functions (d) All of these
ab

 [Ans. (d) All of these] Consider the following statement


2. The duration for which a variable is alive is 1. Assertion : The fundamental concept of access
called its ________. control is that minimizes risk to the object.
(a) End time (b) Life time  Reason : Access control is a security
ur

(c) Scope time (d) Visible time technique that regulates who or what can view
 [Ans. (b) Life time] or use resources in computing environment.
(a) A & R is Fales
3. The scope of a _______ is that part of the code (b) A is True but R is False
.s

where it is visible.
(c) A is False but R is True
(a) Keyword (b) Variable
(d) A & R is True [Ans. (d) A & R is True]
(c) Function (d) Operator
Choose the correct statement
w

 [Ans. (b) Variable]


4. A Function always first look up for a variable 1. (i) A
 Program cannot be divided into modules
name in its _______ scope. that work together to get the output.
w

(a) Local (b) Enclosed (ii) Modules can be separately compiled and
(c) Global (d) Built-in stored in a library.
 [Ans. (a) Local] (iii) Procedure, subroutines and functions are
w

not examples of modules.


5. The inner function can access the variable
of the outer function. This is called _______ (iv) Modules contain instructions, logic and
scope. data
(a) Local (b) Function (a) i and ii (b) ii and iii
(c) Enclosed (d) Global (c) iii and iv (d) ii and iv
 [Ans. (c) Enclosed]  [Ans. (d) ii and iv]

25
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose the incorrect statement 2. Write a note on built-in scope.
Unit I - Chapter 3

Ans. (i) Built-in scope is the widest scope. The


1. (i) There a different types of variable scope
built-in scope has all the names that are
(ii) Enclosed and extended are the type of pre-loaded into the program scope when
variable scope
we start the compiler or interpreter.
(iii) A variable is declared outside of all the

m
(ii) Any variable or module which is defined
function is called global variable
in the library functions of a programming
(iv) Built-in Scope is also called Module scope.
language has Built-in or module scope.
(a) i, iii and iv (b) ii and iii They are loaded as soon as the library files

co
(c) i and ii (d) iii only are imported to the program.
 [Ans. (c) i and ii]
Entire program Library files
associated
Very Short Answers 2 MARKS Built in/module scope
with the software

s.
Disp( )
1. Define variable. Disp 1( ):
Ans. Variable are addresses (references, or pointers), print a
to an object in memory. Disp 1( ):

ok
print a
2. What is the use of LEGB rule? Disp( )
Ans. The LEGB rule is used to decide the order in (iii) 
Normally only Functions or modules
which the scopes are to be searched for scope come along with the software, as packages,
resolution. The scopes are listed below in terms therefore they will come under Built in
o
of hierarchy (highest to lowest).
scope.
3. Name the types of variable scope.
ab

3. Write a note on module.


Ans. (i) Local scope
Ans. (i) A module is a part of a program. Programs
(ii) Enclosed scope are composed of one or more independently
(iii) Global scope developed modules. A single module can
(iv) Built-in scope. contain one or several statements closely
ur

related each other.


4. What is modular programming?
Ans. The process of subdividing a computer program (ii) Modules work perfectly on individual level
into separate sub-programs is called modular and can be integrated with other modules.
.s

programming. A software program can be divided into


modules to ease the job of programming
Short Answers 3 MARKS
and debugging as well.
w

1. How the changes inside the function can’t affect (iii) A program can be divided into small
the variable on the outside of the function in functional modules that work together to
unexpected ways?
get the output. The process of subdividing
w

Ans. (i) Every variable defined in a program has a computer program into separate sub-
global scope. programs is called Modular programming.
(ii) Once defined, every part of your program
(iv) Modular programming enables
can access that variable. But it is a good
w

programmers to divide up the work and


practice to limit a variable's scope to a
debug pieces of the program independently.
single definition.
The examples of modules are procedures,
(iii) This way, changes inside the function can't
subroutines, and functions.
affect the variable on the outside of the
function in unexpected ways.

26
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. How will you ensure the principle of (ii) It is a fundamental concept in security that
data encapsulation in object – oriented minimizes risk to the object.
programming?

Scoping
(iii) In other words access control is a selective
Ans. Public members (generally methods declared restriction of access to data. IN Object
in a class) are accessible from outside the class.
oriented programming languages it is
The object of the same class is required to invoke

m
implemented through access modifiers.
a public method. This arrangement of private
instance variables and public methods ensures (iv) Classical object-oriented languages, such
the principle of data encapsulation. as C++ and Java, control the access to class

co
5. Write a note on access modifiers of a class. members by public, private and protected
keywords.
Ans. (i)  Public members (generally methods
declared in a class) are accessible from (v) Private members of a class are denied
outside the class. access from the outside the class. They can
(ii) Protected members of a class are accessible be handled only from within the class.

s.
from within the class and are also available (vi) Public members (generally methods
to its sub-classes.
declared in a class) are accessible from
(iii) Private members of a class are denied access
outside the class. The object of the same

ok
from outside the class. They can be handled
class is required to invoke a public method.
only from within the class.
This arrangement of private instance
6. Write a short note on types of variable scope. variables and public methods ensures the
Ans. (i)  Public members (generally methods principle of data encapsulation.
o
declared in a class) are accessible from
(vii) Protected members of a class are accessible
outside the class.
from within the class and are also available
(ii) A variable which is declared outside of all
ab

to its sub-classes. No other process is


the functions in a program is known as
global variable. permitted access to it. This enables specific
(iii) 
A variable which is declared inside a resources of the parent class to be inherited
function which contains another function by the child class.
ur

definition with in it, the inner function (viii) Python doesn't have any mechanism that
can also access the variable of the outer effectively restricts access to any instance
function. This scope is called enclosed variable or method. Python prescribes a
scope. convention of prefixing the name of the
.s

(iv) Built-in scope the widest scope has all the variable or method with single or double
names that are pre-loaded into program underscore to emulate the behaviour of
scope when we start the compiler or protected and private access specifiers.
interpreter.
w

(ix) All members in a Python class are public


Long Answers 5 MARKS by default, whereas by default in C++ and
1. Explain the concept access control. java they are private. Any member can be
w

accessed from outside the class environment


Ans. (i) Access control is a security technique that in Python which is not possible in C++ and
regulates who or what can view or use java.
resources in a computing environment.
w



27
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

  
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Chapter
 

4 ALGORITHMIC STRATEGIES

m

co
s.
CHAPTER SNAPSHOT

ok
4.1 Introduction to Algorithmic strategies
4.1.1. Characteristics of an Algorithm
4.1.2. Writing an Algorithm
4.1.3. Analysis of Algorithm
o
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
4.6 Dynamic programming
w

4.6.1. Fibonacci Series – An example


4.6.2. Fibonacci Iterative Algorithm with Dynamic programming approach
w

[28]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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

m
1. The word comes from the name of a Persian (c) Memoization
mathematician Abu Ja’far Mohammed ibn-i (d) Greedy
Musa al Khowarizmi is called? [PTA-6]
[Ans. (a) Overlapping subporblems]
(a) Flowchart (b) Flow

co
(c) Algorithm (d) Syntax 10. In dynamic programming, the technique of
[Ans. (c) Algorithm] storing the previously calculated values is
2. From the following sorting algorithms which called ? [HY-2019]
algorithm needs the minimum number of (a) Saving value property

s.
swaps? (b) Storing value property
(a) Bubble sort (b) Quick sort (c) Memoization
(c) Merge sort (d) Selection sort
(d) Mapping [Ans. (c) Memoization]
[Ans. (d) Selection sort]

ok
3. Two main measures for the efficiency of an Part - II
algorithm are Answer the following questions
(a) Processor and memory
(b) Complexity and capacity
 (2 marks)
o
(c) Time and space (d) Data and space 1. What is an Algorithm?
[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)]
5. From the following sorting algorithms which Ans. (i) Pseudo code is an informal high level
ur

has the lowest worst case complexity? description of the operations principle of a
(a) Bubble sort (b) Quick sort computer program or other algorithm.
(c) Merge sort (d) Selection sort (ii) It uses the structural conventions of a
[Ans. (c) Merge sort] normal programming language, but is
.s

intended for human reading rather than


6. Which of the following is not a stable sorting
machine reading.
algorithm?
(a) Insertion sort (b) Selection sort 3. Who is an Algorist?
w

(c) Bubble sort (d) Merge sort Ans. Algorist may refer to
[Ans. (b) Selection sort] (i) A person skilled in the technique of
7. Time complexity of bubble sort in best case is performing basic decimal arithmetic,
w

 [PTA-1] known as algorism.


(a) θ (n) (b) θ (nlogn) (ii) A person skilled in the design of algorithms.
(c) θ (n2) (d) θ (n(logn) 2) (iii) An Algorithmic artist.
w

[Ans. (a) θ (n)]


4. What is Sorting?
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
(c) Worst case (d) NULL case techniques in algorithms are Bubble sort, Quick
[Ans. (b) Average case] sort, Heap sort, Selection sort, Insertion sort.

29
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5. What is searching? Write its types. 4. Write a note on Asymptotic notation.
Unit I - Chapter 4

 [Govt. MQP-2019; HY-2019]  [QY-2019]


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

m
(i) Linear Search
notations are mostly used to represent time
complexity of algorithms:
(ii) Binary Search
(i) Big O : Big O is often used to describe the
Part - III

co
worst-case of an algorithm.
Answer the following questions
(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

s.
Ans. (i) Input Omega is used to describe the lower bound
(best-case).
(ii) Output
(iii) Big Θ : When an algorithm has a complexity

ok
(iii) Finiteness
(iv) Definiteness with lower bound = upper bound, say that
an algorithm has a complexity O (n log
(v) Effectiveness
n) and Ω (n log n), it’s actually has the
(vi) Correctness
complexity Θ (n log n), which means the
o
(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?
(xi) Independent
Ans. (i) Dynamic programming is an algorithmic
2. Discuss about Algorithmic complexity and its design method that can be used when the
ur

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
(ii) Dynamic programming approach is similar
by the algorithm in terms of n as the size of input
.s

data. to divide and conquer. The given problem


(i) Time Complexity : The Time complexity is divided into smaller and yet smaller
of an algorithm is given by the number of possible sub-problems.
w

steps taken by the algorithm to complete (iii) Dynamic programming is used whenever
the process.
problems can be divided into similar
(ii) Space Complexity : Space complexity sub-problems. So that their results can be
w

of an algorithm is the amount of memory


required to run to its completion. re-used to complete the process.

3. What are the factors that influence time and (iv) Dynamic programming approaches are
used to find the solution in optimized way.
w

space complexity?
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
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Part - IV Pseudo code :

Algorithmic strategies
(i) Traverse the array using for loop
Answer the following questions
(ii)  In every iteration, compare the target
 (5 marks) search key value with the current value of
1. Explain the characteristics of an algorithm. the list.
■ 

m
If the values match, display the
Ans.  [PTA-5; HY-2019]
current index and value of the array
Input Zero or more quantities to be ■ If the values do not match, move on
supplied. to the next array element.

co
Output At least one quantity is produced. (iii) If no match is found, display the search
Finiteness element not found.
Algorithms must terminate after
finite number of steps. Example
Definiteness All operations should be well To search the number 25 in the array given

s.
defined. For example operations below, linear search will go step by step in a
involving division by zero or sequential order starting from the first element
taking square root for negative in the given array if the search element is found
number are unacceptable. that index is returned otherwise the search is

ok
Effectiveness Every instruction must be carried continued till the last index of the array. In this
out effectively. example number 25 is found at index number 3.
Correctness The algorithms should be error index 0 1 2 3 4
free. values 10 12 20 25 30
o
Simplicity East to implement. Example 1 :
Unambiguous Algorithm should be clear and Input: values[] = {5, 34, 65, 12, 77, 35}
ab

unambiguous. Each of its steps target = 77


and their inputs/outputs should Output: 4
be clear and must lead to only one Example 2:
meaning. Input: values[] = {101, 392, 1, 54, 32, 22, 90, 93}
ur

Feasibility Should be feasible with the target = 200


available resources. Output: -1 (not found)
Portable An algorithm should be generic,
independent of any programming 3. What is Binary search? Discuss with example.
.s

language or an operating system Ans. Binary search : Binary search also called half-
able to handle all range of inputs. interval search algorithm. It finds the position
Independent An algorithm should have of a search element within a sorted array. The
step-by-step directions, which binary search algorithm can be done as divide-
w

should be independent of any and-conquer search algorithm and executes in


programming code. logarithmic time.
Pseudo code for Binary search :
2. Discuss about Linear search algorithm.
w

Start with the middle element:


 [PTA-1] (i) If the search element is equal to the middle
Ans. (i) Linear search also called sequential search is element of the array i.e., the middle value =
a sequential method for finding a particular number of elements in array/2, then return
w

value in a list. the index of the middle element.


(ii) If not, then compare the middle element
(ii) This method checks the search element with
with the search value,
each element in sequence until the desired
element is found or the list is exhausted. In (iii) If the search element is greater than the
this searching algorithm, list need not be number in the middle index, then select
ordered. the elements to the right side of the middle
index, and go to Step-1.

31
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iv) 
If the search element is less than the (viii) The value stored at location or index 7 is
Unit I - Chapter 4

number in the middle index, then select not a match with search element, rather it is
the elements to the left side of the middle more than what we are looking for. So, the
index, and start with Step-1.
search element must be in the lower part
(v) When a match is found, display success from the current mid value location
message with the index of the element

m
matched.
(vi) If no match is found for all comparisons, 10 20 30 40 50 60 70 80 90 99
then display unsuccessful message. 0 1 2 3 4 5 6 7 8 9
Binary Search Working principles : (ix) The search element still not found. Hence,

co
(i) List of elements in an array must be sorted we calculated the mid again by using the
first for Binary search. The following formula.
example describes the step by step operation
of binary search. high = mid -1
mid = low + (high - low)/2
(ii) Consider the following array of elements,

s.
the array is being sorted so it enables to do Now the mid value is 5.
the binary search algorithm. Let us assume
that the search element is 60 and we need

ok
to search the location or index of search 10 20 30 40 50 60 70 80 90 99
element 60 using binary search. 0 1 2 3 4 5 6 7 8 9
(x) Now we compare the value stored at
10 20 30 40 50 60 70 80 90 99
0 1 2 3 4 5 6 7 8 9 location 5 with our search element. We
o
found that it is a match.
(iii) First, we find index of middle element of
the array by using this formula : 10 20 30 40 50 60 70 80 90 99
ab

mid = low + (high - low) / 2 0 1 2 3 4 5 6 7 8 9


(iv) Here it is, 0 + (9 - 0 ) / 2 = 4 (fractional part
ignored). So, 4 is the mid value of the array.
(xi) We can conclude that the search element 60

is found at location or index 5. For example
ur

if we take the search element as 95, For this


10 20 30 40 50 60 70 80 90 99
0 1 2 3 4 5 6 7 8 9 value this binary search algorithm return
(v) Now compare the search element with the unsuccessful result.
value stored at mid value location 4. The
.s

value stored at location or index 4 is 50, 4. Explain the Bubble sort algorithm with
which is not match with search element. As example. [PTA-6]
the search value 60 is greater than 50. Ans. Bubble sort algorithm:
w

(i) Bubble sort is a simple sorting algorithm.


10 20 30 40 50 60 70 80 90 99
The algorithm starts at the beginning of the
0 1 2 3 4 5 6 7 8 9
list of values stored in an array. It compares
each pair of adjacent elements and swaps
w

(vi) Now we change our low to mid + 1 and find


the new mid value again using the formula. them if they are in the unsorted order.
low to mid + 1 (ii) This comparison and passed to be continued
until no swaps are needed, which indicates
w

mid = low + (high - low) / 2 that the list of values stored in an array is
(vii) Our new mid is 7 now. We compare the sorted. The algorithm is a comparison sort,
value stored at location 7 with our target is named for the way smaller elements
value 31. "bubble" to the top of the list.
(iii) Although the algorithm is simple, it is too
slow and less efficient when compared to
10 20 30 40 50 60 70 80 90 99
insertion sort and other sorting methods.
0 1 2 3 4 5 6 7 8 9

32
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iv) Assume list is an array of n elements. The (iii) Dynamic programming is used whenever
swap function swaps the values of the given problems can be divided into similar

Algorithmic strategies
array elements. sub-problems. So that their results can be
Pseudo code : re-used to complete the process.
(i) Start with the first element i.e., index = 0, (iv) Dynamic programming approaches are
compare the current element with the next used to find the solution in optimized way.

m
element of the array. For every inner sub problem, dynamic
(ii) If the current element is greater than the algorithm will try to check the results of the
next element of the array, swap them. previously solved sub-problems.
(v) The solutions of overlapped sub-problems

co
(iii) If the current element is less than the next
or right side of the element, move to the are combined in order to get the better
next element. Go to Step 1 and repeat until solution.
end of the index is reached. Steps to do Dynamic programming :
(iv) Let's consider an array with values {15, 11, (i)  The given problem will be divided into

s.
16, 12, 14, 13} Below, we have a pictorial smaller overlapping sub-problems.
representation of how bubble sort will sort
(ii) An optimum solution for the given problem
the given array.
can be achieved by using result of smaller

ok
15>11
So interchange 15 11 16 12 14 13 sub-problem.
(iii) Dynamic algorithms uses Memoization.
15>16
15 11 16 12 14 13
No swapping Fibonacci Series – An example :
(i) Fibonacci series generates the subsequent
o
16>12
11 15 16 12 14 13
number by adding two previous numbers.
So interchange Fibonacci series starts from two numbers −
ab

Fib 0 & Fib 1. The initial values of Fib 0 &


16>14 11 15 12 16 14 13
Fib 1 can be taken as 0 and 1.
So interchange
(ii) Fibonacci series satisfies the following
16>13 conditions :
11 15 12 14 16 13
So interchange Fibn = Fibn-1 + Fibn-2
ur

(iii) Hence, a Fibonacci series for the n value 8


11 15 12 14 13 16
can look like this
Fib8 = 0 1 1 2 3 5 8 13
(v) The above pictorial example is for
Fibonacci Iterative Algorithm with Dynamic
.s

iteration–1. Similarly, remaining iteration


can be done. The final iteration will give the programming approach : The following
sorted array. At the end of all the iterations example shows a simple Dynamic programming
we will get the sorted values in an array as approach for the generation of Fibonacci series.
w

given below : Initialize f0=0, f1 =1


11 12 13 14 15 16 step-1: Print the initial values of Fibonacci f0
and f1
w

5. Explain the concept of Dynamic programming step-2: Calculate fibanocci fib ← f0 + f1


with suitable example. step-3: Assign f0← f1, f1← fib
(i) Dynamic programming is an algorithmic step-4:  Print the next consecutive value of
fibanocci fib
w

design method that can be used when the


solution to a problem can be viewed as the step-5: Goto step-2 and repeat until the specified
result of a sequence of decisions. number of terms generated
(ii) Dynamic programming approach is similar For example if we generate fibobnacci series
to divide and conquer. The given problem upto 10 digits, the algorithm will generate the
series as shown below:
is divided into smaller and yet smaller
The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55.
possible sub-problems.

33
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. What are the different phases of analysis and
PTA Questions and Answers
Unit I - Chapter 4

performance evaluation of an algorithm?


1 MARK  [PTA-5]
Ans. Analysis of algorithms and performance
1. Step by step procedure for solving a given evaluation can be divided into two different
problem: [PTA-2] phases:

m
(a) Proram (b) Pseudo Code
(i) A Priori estimates : This is a theoretical
(c) Flowchart (d) Algorithm performance analysis of an algorithm.
 [Ans. (d) Algorithm] Efficiency of an algorithm is measured by
2. Which of the following is not a characteristic

co
assuming the external factors.
of an algorithm? [PTA-3]
(ii) A Posteriori testing : This is called
(a) Input (b) Program performance measurement. In this analysis,
(c) Finiteness (d) Simplicity actual statistics like running time and
 [Ans. (b) Program] required for the algorithm executions are

s.
3. This is a theoretical performance analysis of collected.
an algorithm. [PTA-4]
(a) Priori estimates (b) Posteriori testing 4. What are the factors that measure the
(c) Space factor (d) Time factor execution time of an algorithm? [PTA-6]

ok
 [Ans. (a) Priori estimates] Ans. The space required by an algorithm is equal to
4. Which of the following algorithmic approach the sum of the following two components:
is similar to divide and conquer approach? (i) A fixed part is defined as the total
 [PTA-5] space required to store certain data and
(a) Insertion sorting variables for an algorithm. For example,
o
(b) Dynamic programming simple variables and constants used in an
(c) Selection searching algorithm.
ab

(d) Bubble programming (ii) A variable part is defined as the total


 [Ans. (b) Dynamic programming] space required by variables, which sizes
depends on the problem and its iteration.
3 MARKS For example: recursion used to calculate
1. Write a pseudo code for bubble sort algorithm. factorial of a given value n.
ur

 [PTA-3]
5 MARKS
Ans. (i) Start with the first element i.e., index = 0,
compare the current element with the next 1. Explain about Complexity of an algorithm.
element of the array.
.s

 [PTA-3]
(ii) If the current element is greater than the Ans. Suppose A is an algorithm and n is the size
next element of the array, swap them. of input data, the time and space used by the
(iii) If the current element is less than the next algorithm A are the two main factors, which
w

or right side of the element, move to the decide the efficiency of A.


next element. Go to Step 1 and repeat until
(i) Time Factor : Time is measured by
end of the index is reached.
counting the number of key operations like
2. Write the pseudo code for linear search.
w

comparisons in the sorting algorithm.


 [PTA-4]
(ii) Space Factor : Space is measured by the
Ans. (i) Traverse the array using 'for loop' maximum memory space required by the
(ii) In every iteration, compare the target algorithm. The complexity of an algorithm
w

search key value with the current value of f (n) gives the running time and/or the
the list. storage space required by the algorithm in
(iii) If the values match, display the current terms of n as the size of input data.
index and value of the array
(iv) If the values do not match, move on to the (iii) Time Complexity : The Time complexity
next array element. of an algorithm is given by the number of
(v) If no match is found, display the search steps taken by the algorithm to complete
element not found. the process.

34
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iv) Space Complexity : Space complexity of (i)  After that, next smallest element will be
an algorithm is the amount of memory searched from an array. Now we will get

Algorithmic strategies
required to run to its completion. The space 13 as the smallest, so it will be then placed
required by an algorithm is equal to the at the second position.
sum of the following two components:
■ A fixed part is defined as the total (ii) Then leaving the first element, next
smallest element will be searched, from

m
space required to store certain data and
variables for an algorithm. For example, the remaining elements. We will get 13 as
simple variables and constants used in an the smallest, so it will be then placed at the
algorithm. second position.

co
■ A variable part is defined as the total (iii) 
Then leaving 11 and 13 because they are at
space required by variables, which sizes the correct position, we will search for the
depends on the problem and its iteration.
next smallest element from the rest of the
For example: recursion used to calculate
factorial of a given value n. elements and put it at third position and

s.
2. Write the pseudo code for selection sort keep doing this until array is sorted.
algorithm. [PTA-4] Government Exam Questions and Answers
Ans. The selection sort is a simple sorting algorithm

ok
that improves on the performance of bubble sort 1 MARK
by making only one exchange for every pass
through the list. 1. Big is Ω the reverse of [Govt. MQP-2019]
Pseudo code : (a) Big O (b) Big Θ
(i) Start from the first element i.e., index-0, (c) Big A (d) Big S
o
we search the smallest element in the array, [Ans. (a) Big O]
and replace it with the element in the first 2. What is another name for Binary search?
position.
ab

 [QY-2019]
(ii) Now we move on to the second element (a) Linear (b) Half interval
position, and look for smallest element
(c) Decimal (d) Boolean
present in the sub-array, from starting
[Ans. (b) Half interval]
index to till the last index of sub - array.
(iii) Now replace the second smallest identified 5 MARKS
ur

in step-2 at the second position in the or


original array, or also called first position in 1. Explain the selection Sort Algorithm with an
the sub array. example. [QY-2019]
(iv) This is repeated, until the array is completely Ans. (i) Let us assume a list of n number of values
.s

sorted. stored in an array. Suppose if we want to


Let's consider an array with values {13, 16, 11, search a particular element in this list, the
18, 14, 15} algorithm that search the key element in
w

Below, we have a pictorial representation of how the list among n elements, by comparing
selection sort will sort the given array. the key element with each element in the
Initial At the At the end At the At the end At the list sequentially.
array end First Second Fourth (ii) The best case would be if the first element in
w

pass pass pass pass pass


13
the list matches with the key element to be
11 11
11 11 11
searched in a list of elements. The efficiency
16 16 13 13 13 13 in that case would be expressed as O(1)
w

11 16
because only one comparison is enough.
13 14 14 14
(iii) Similarly, the worst case in this scenario
18 18 18 18 15 15
would be if the complete list is searched and
14 14 14 16 16 16 the element is found only at the end of the
15 15 15 15 18 18 list or is not found in the list. The efficiency
of an algorithm in that case would be

In the first pass, the smallest element will be 11, expressed as O(n) because n comparisons
so it will be placed at the first position. required to complete the search.
35
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iv) The average case efficiency of an algorithm 6. Which of the following is not a type of
Unit I - Chapter 4

can be obtained by finding the average searching technique?


number of comparisons as given below: (i) Linear (ii) Binary
Minimum number of comparisons = 1 (iii) Selection (iv) Merge
Maximum number of comparisons = n (a) Only i (b) Only ii

m
If the element not found then (c) Only iii (d) iii and iv
maximum number of comparison = n [Ans. (d) iii and iv]
Therefore, average number
of comparisons = (n + 1)/2 7. Which of the following is not a sorting

co
(v) Hence the average case efficiency will be
technique?
expressed as O (n). (a) Bubble (b) Binary
(c) Insertion (d) Quick
additional questions and Answers  [Ans. (b) Binary]

s.
Choose the Correct Answer 1 MARK 8. The way of defining an algorithm is called
(a) Pseudo strategy
1. Which of the following is a finite set of
(b) Programmic strategy

ok
instructions to accomplish a particular task?
(c) Algorithmic strategy
(a) Flowchart (b) Functions
(d) Data structured strategy
(c) Algorithm (d) Abstraction
 [Ans. (c) Algorithmic strategy]
 [Ans. (c) Algorithm]
9. Which characteristics of algorithm defined the
o
2. Which of the following are the characteristics operation involving division by zero?
of an algorithm?
(a) Finiteness (b) Definiteness
ab

(i) Definiteness
(ii) Correctness (c) Input (d) Correctness
(iii) Effectiveness  [Ans. (b) Definiteness]
(a) i, ii (b) ii, iii 10. Which characteristics of an algorithm should
ur

(c) Only ii (d) i, ii and iii be generic, independent of any programming


[Ans. (d) i, ii and iii] language?
3. Which of the following is not a characteristic (a) Independent (b) Portable
of an algorithm?
.s

(c) Feasibility (d) Unambiguous


(a) Definiteness (b) Correctness
[Ans. (b) Portable]
(c) Data structure (d) Effectiveness
 [Ans. (c) Data structure] 11. Which of the following could be designed to
w

get a solution of a given problem?


4. Which of the following is not an example of (a) Program (b) Algorithm
data structures? (c) Flowchart (d) Input/Output
w

(a) Control statement (b) Structure  [Ans. (b) Algorithm]


(c) List (d) Dictionary 12. An algorithm that yields expected output for a
 [Ans. (a) Control statement] valid input is called an
w

5. Which of the following is an example of data (a) Algorithmic Solution


structures? (b) Algorithmic Structure
(a) List (b) Tuple (c) Algorithmic Strategy
(c) Dictionary (d) All of these. (d) Algorithmic Procedure
 [Ans. (d) All of these]  [Ans. (a) Algorithmic Solution]

36
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


13. Performance measurement of an algorithm is 20. Which of the following component is defined
called as the total space required to store certain data

Algorithmic strategies
(a) Posteriori testing (b) Priori estimates and variables for an algorithm?
(c) Efficiency testing (a) Time part (b) Variable part
(d) Algorithmic analysis (c) Fixed part (d) Memory part
 [Ans. (a) Posteriori testing]

m
 [Ans. (c) Fixed part]
14. An estimation of the time and space 21. Which of the following component is defined
complexities of an algorithm is called as the total space required by variables, which
(a) Algorithmic solution

co
sizes depends on the problem and its iteration?
(b) Algorithmic Strategy (a) Variable part (b) Time part
(c) Algorithmic performance (c) Fixed part (d) Efficiency part
(d) Algorithmic analysis [Ans. (a) Variable part]
 [Ans. (d) Algorithmic analysis]

s.
22. Time and Space complexity could be
15. Efficiency of an algorithm decided by considered for an
(a) Time, Space (a) Algorithmic strategy

ok
(b) Definiteness, portability (b) Algorithmic analysis
(c) Priori, Postriori (c) Algorithmic solution
(d) Input/output  [Ans. (a) Time, Space] (d) Algorithmic efficiency
16. The number of steps taken by the algorithm to  [Ans. (d) Algorithmic efficiency]
o
complete the process is known as
23. How many factors are used to measure the
(a) Time complexity of an algorithm time efficiency of an algorithm?
ab

(b) Space complexity of an algorithm


(a) Two (b) Three
(c) Efficiency of an algorithm
(c) Six (d) Many
(d) Performance analysis of an algorithm [Ans. (d) Many]
 [Ans. (a) Time complexity of an algorithm] 24. Which of the following is not a factor use a to
ur

17. Which of the following should be written measure the time efficiency of an algorithm?
for the selected programming language with (a) Speed of the machine
specific syntax? (b) Operating system
(a) Algorithm (b) Pseudocode (c) Designing algorithm
.s

(c) Process (d) Program (d) Programming language


 [Ans. (d) Program] (e) Volume of data required
 [Ans. (c) Designing algorithm]
w

18. The amount of memory required to run an


algorithm completion is known by 25. How many asymptotic notations are mostly
(a) Efficiency of an algorithm used to represent time complexity of
algorithms?
w

(b) Performance analysis of an algorithm


(a) Three (b) Two
(c) Space complexity of an algorithm (c) One (d) Many
(d) Time complexity of an algorithm  [Ans. (a) Three]
w

 [Ans. (c) Space complexity of an algorithm]


26. Which of the following notation is often used
19. How many components required to find the to describe the worst-case fan algorithm?
space required by an algorithm? (a) Big Ω (b) Big µ
(a) 4 (b) 3 (c) 6 (d) 2 (c) Big O (d) Big α
 [Ans. (d) 2]  [Ans. (c) Big O]

37
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


27. Which of the following is the reverse of Big O? 36. Bubble sort is also called
Unit I - Chapter 4

(a) Big Ω (b) Big µ (a) Sequential sort


(c) Big symbol (d) Big b (b) Quick sort
 [Ans. (a) Big Ω] (c) Half-interval sort
28. 0(1) is an example of (d) Comparison sort

m
(a) best case (b) worst case  [Ans. (d) Comparison sort]
(c) Average case (d) Null casd
 [Ans. (a) best case] 37. Which of the following sorting algorithm is

co
too slow and less efficient?
29. 0(n) is an example of
(a) best case (b) Average case (a) Bubble (b) Selection
(c) worst case (d) Null case (c) Quick (d) Merge
 [Ans. (c) worst case]  [Ans. (a) Bubble]

s.
30. Linear search is also called 38. Which sorting algorithm compares each pair
(a) Sequential search (b) Quick search of adjacent elements and swaps them if they
(c) Binary search (d) Selection search are in the unsorted order?

ok
[Ans. (a) Sequential search] (a) Selection (b) Merge
31. Which of the following method checks the (c) Insertion (d) None of these
search element with each element in sequence?  [Ans. (d) None of these]
(a) Bubble search (b) Binary search
o
(c) Linear search (d) None of these 39. Which sorting algorithm sort is by making
 [Ans. (c) Linear search] only one exchange for every pass through the
list?
ab

32. Binary search also called (a) Bubble (b) Selection


(a) Sequential search
(c) Comparison (d) Merge
(b) Half-interval search
 [Ans. (b) Selection]
(c) Unordered search
ur

(d) Full-interval search 40. Which sorting algorithm repeatedly selects


 [Ans. (b) Half-interval search] the next smallest element and swaps in into
the right place for every pass?
33. Which of the following algorithm finds the (a) Bubble sort (b) Sequential sort
position of a search element within a sorted
.s

(c) Selection sort (d) Heap sort


array?
[Ans. (c) Selection sort]
(a) Binary search (b) Linear search
(c) Sequential search (d) List search 41. Which sorting techniques working by taking
w

 [Ans. (a) Binary search] elements from the list one by one and inserting
them in their correct position into a new
34. Which search algorithm can be done as divided sorted list?
w

and conjurer search algorithm? (a) Bubble (b) Selection


(a) Half-interval (b) linear (c) Merge (d) Insertion
(c) Sequential (d) Bubble  [Ans. (d) Insertion]
w

 [Ans. (a) Half-interval]


42. Which of the following programming is used
35. Which of the following search algorithm whenever problems can be divided into similar
executes in logarithmic time? sub-problems?
(a) Linear (b) Sequential (a) Dynamic (b) Object oriented
(c) Binary (d) Half-interval (c) Modular (d) Procedural
(e) c or d[Ans. (e) c or d]  [Ans. (a) Dynamic]

38
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


43. In which programming the solutions of 6. Space required by an algorithm = Fixed part
overlapped sub-problems are combined in + ______

Algorithmic strategies
order to get the better solution? (a) Constant part (b) Variable part
(a) Object oriented (b) Procedural (c) Time part (d) Second part
(c) Dynamic (d) Modular  [Ans. (b) Variable part]
 [Ans. (c) Dynamic] 7. Recursion used to calculate factorial of a given

m
value n in algorithm is an example of ______
44. Which of the following algorithm used
component
memorization?
(a) Fixed part (b) Variable part

co
(a) Efficient (b) Dynamic (c) Operator part (d) Time part
(c) Effective (d) Modular  [Ans. (b) Variable part]
 [Ans. (b) Dynamic]
8. Simple variables and constants used in an
45. Which of the following optimization technique algorithm is an example of ______ component.

s.
used in dynamic algorithms. (a) Time part (b) Variable part
(a) Memorization (c) Factor part (d) Fixed part
(b) Composition  [Ans. (d) Fixed part]

ok
(c) Specification
 9. The ____ of an algorithm is defined as the
(d) Decomposition [Ans. (a) Memorization] number of computational resources used by
the algorithm.
Choose and fill in the blanks (a) Simplicity (b) Efficiency
1. Data are maintained and manipulated (c) Feasibility (d) Potable
o
effectively through ______.  [Ans. (b) Efficiency]
(a) Algorithm (b) Data Structures 10. _____ are languages that uses meaningful
ab

(c) Pseudocode (d) Program statements about time and space complexity?
(a) Time and space trade
 [Ans. (b) Data Structures]
(b) Asymptotic notations
2. Each of algorithm steps and there inputs/ (c) Complexity notations
outputs should be clear and must lead to (d) Algorithmic notations
ur

only one meaning refers to the algorithm  [Ans. (b) Asymptotic notations]
characteristics ______. 11. _____ is used to describe the upper bound of a
(a) Unambiguous (b) Feasibility asymptotic function.
(a) Big µ (b) Big O
.s

(c) Independent (d) Effectiveness


(c) Big Ω (d) Big β
 [Ans. (a) Unambiguous]
 [Ans. (b) Big O]
3. Algorithm resembles a ______ which can be 12. ______ is used to describe the lower bound of
w

implemented in any programming language. asymptotic function.


(a) Solution (b) Program (a) Big Alpha (b) Big Beta
(c) Pseudocode (d) Function (c) Big O (d) Big Omega
w

 [Ans. (c) Pseudocode]  [Ans. (d) Big Omega]


4. Performance evaluation of an algorithm can Choose the correct statement
be divided into ______ different phases. 1. Choose the correct typical algorithm from the
w

(a) 3 (b) 4 (c) 2 (d) 1 following.


 [Ans. (c) 2] (a) Input → Output → Process
(b) Output → Input → Process
5. Efficiency of an algorithm is measured by ___
(c) Process → Input → Output
factors.
(d) Input → Process → Output
(a) 3 (b) 4 (c) 2 (d) 1
 [Ans. (c) 2]  [Ans. (d) Input → Process → Output]

39
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Choose the correct pair from the following Very Short Answers 2 MARKS
Unit I - Chapter 4

(a) Big O – Best case


1. Give an example of data structures.
(b) Big Ω - Worst case
Ans. Examples for data structures are arrays,
(c) Big Θ - Average case structures, list, tuples, dictionary.
(d) Big µ - First case 2. What in algorithmic strategy? Give an

m
 [Ans. (c) Big Θ - Average case] example.
Choose the incorrect statement Ans. (i) The way of defining an algorithm is called
1. (i) Linear search is also called sequential search algorithmic strategy.

co
(ii) Bubble sort is also called comparison sort (ii) For example to calculate factorial for
the given value n then it can be done by
(iii) Dynamic algorithms does not uses
defining the function to calculate factorial
optimization technique memorization. once for the iteration-1 then it can be called
(iv) Binary search algorithm can not be done as recursively until the number of required

s.
divide and conquer search algorithm. iteration is reached.
(a) i and ii (b) ii and iii 3. What is algorithmic solution?
(c) iii and iv (d) Only iv Ans. An algorithm that yields expected output for a

ok
valid input is called an algorithmic solution.
 [Ans. (c) iii and iv]
2. (a) P
 rior estimates is a theoretical performance 4. How the efficiency of an algorithm is defined?
Ans. Efficiency of an algorithm is defined by the
analysis of an algorithm utilization of time and space complexity.
o
(b) Posteriori testing is called performance
5. What does analysis of an algorithm deals with?
analysis of an algorithm. Ans. (i) Analysis of an algorithm usually deals with
ab

(c) Efficiency of an algorithm decided by time the running and execution time of various
and space factor. operations involved.
(d) Space required by an algorithm is equal to (ii) The running time of an operation is
the sum of fixed part and variable part calculated as how many programming
ur

instructions is executed per operation.


[Ans. (b) Posteriori testing is called
 performance analysis of an algorithm.] 6. What is algorithm analysis?
Ans. An estimation of the time and space complexities
3. (i) In Algorithm, All operations in should be of an algorithm for varying input sizes is called
.s

well defined algorithm analysis.


(ii) Algorithms must not terminate after finite
number of steps. 7. How the time efficiency of an algorithm is
(iii) In algorithms, errors are acceptable measured. Give an example.
w

Ans. The time efficiency of an algorithm is measured


(iv) An algorithm should have step-by-step
by different factors. For example, write a program
directions.
for a defined algorithm, execute it by using any
(a) i and ii (b) i, iii and iv
w

programming language, and measure the total


(c) ii and iii (d) iii only time it takes to run.
 [Ans. (c) ii and iii]
8. What is algorithmetic strategy?
Choose the incorrect pair
w

Ans. A way of designing algorithm is called algorithmic


1. Choose the incorrect pair from the following strategy.
(a) Big O – Worst case 9. What is best algorithm?
(b) Big Ω - First case Ans. The best algorithm to solve a given problem is
(c) Big µ - Best case one that requires less space in memory and takes
(d) Big α - Average case less time to execute its instructions to generate
 [Ans. (b) Big Ω - First case] output.

40
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. What are asymptotic notations? 3. Write a note on time/space trade off.

Algorithmic strategies
Ans. Asymptotic Notations are languages that uses Ans. (i) A space-time or time-memory trade off
meaningful statements about time and space is a way of solving in less time by using
complexity. more storage space or by solving a given
11. What are the three asymptotic notations used algorithm in very little space by spending

m
to represent time complexity of algorithms? more time.
Ans. (i) Big O (ii) To solve a given programming problem,
many different algorithms may be used.
(ii) Big W
Some of these algorithms may be extremely

co
(iii) Big μ time-efficient and others extremely space-
12. Write a note on Big omega asymptotic efficient.
notation. (iii) Time/space trade off refers to a situation
Ans. Big Omega is the reverse Big O, if Big O is used where you can reduce the use of memory
at the cost of slower program execution,

s.
to describe the upper bound (worst - case) of
a asymptotic function, Big Omega is used to or reduce the running time at the cost of
describe the lower bound (best-case). increased memory usage.

13. Write a note on memorization. 4. Write the different factors in which the time

ok
Ans. Memoization or memoisation is an optimization efficiency of an algorithm its measured.
technique used primarily to speed up computer Ans. The execution time that you measure in this case
programs by storing the results of expensive would depend on a number of factors such as:
function calls and returning the cached result (i) Speed of the machine
o
when the same inputs occur again. (ii) Compiler and other system Software tools
Short Answers 3 MARKS (iii) Operating System
ab

(iv) Programming language used


1. List the manipulation manipulated effectively (v) Volume of data required
through data structures by algorithm.
5. Write a pseudo code for Binary search.
Ans.
Ans. Start with the middle element:
Search To search an item in a data structure
ur

(i) If the search element is equal to the middle


using linear and binary search.
element of the array i.e., the middle value =
Sort To sort items in a certain order using the number of elements in array/2, then return
methods such as bubble sort, insertion the index of the middle element.
sort, selection sort, etc.
.s

(ii) If not, then compare the middle element


Insert To insert an item (s) in a data structure.
with the search value,
Update To updata an existing item (s) in a data (iii) If the search element is greater than the
w

structure. number in the middle index, then select


Delete To delete an existing item (s) in a data the elements to the right side of the middle
structure. index, and go to Step-1.
w

2. Design an algorithm to find square of the (iv)  If the search element is less than the
given number and display the result. number in the middle index, then select
Ans. The algorithm can be written as: the elements to the left side of the middle
w

Step 1 – start the process index, and start with Step-1.


Step 2 – get the input x (v) When a match is found, display success
Step 3 – calculate the square by multiplying the message with the index of the element
input value ie., square ← x* x matched.
Step 4 − display the result square (vi) If no match is found for all comparisons,
Step 5 − stop then display unsuccessful message.

41
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


6. Write a pseudo code for selection sort. For example if we generate fibobnacci series
Unit I - Chapter 4

Ans. (i) Start from the first element i.e., index-0, upto 10 digits, the algorithm will generate the
we search the smallest element in the array, series as shown below:
and replace it with the element in the first The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55
position. Long Answers 5 MARKS

m
(ii) Now we move on to the second element
position, and look for smallest element 1. Write a note on Efficiency of an algorithm.
present in the sub-array, from starting
Ans. (i) Computer resources are limited that should
index to till the last index of sub - array.
be utilized efficiently. The efficiency of

co
(iii) Now replace the second smallest identified an algorithm is defined as the number
in step-2 at the second position in the or
of computational resources used by the
original array, or also called first position in
the sub array. algorithm.
(ii) An algorithm must be analyzed to

s.
7. Write a pseudo code for Insertion sort. determine its resource usage. The efficiency
Ans. Step 1 − If it is the first element, it is already of an algorithm can be measured based on
sorted. the usage of different resources.
Step 2 − Pick next element

ok
(iii) For maximum efficiency of algorithm
Step 3 − Compare with all elements in the sorted we wish to minimize resource usage. The
sub-list
important resources such as time and space
Step 4 − Shift all the elements in the sorted
sub-list that is greater than the value to complexity cannot be compared directly,
so time and space complexity could be
o
be sorted
Step 5 − Insert the value considered for an algorithmic efficiency.
Step 6 − Repeat until list is sorted.
ab

Method for determining Efficiency :


8. Write the steps to do dynamic programming.
(i) The efficiency of an algorithm depends on
Ans. (i) 
The given problem will be divided into how efficiently it uses time and memory
smaller overlapping sub-problems.
space.
ur

(ii) An optimum solution for the given problem


(ii) The time efficiency of an algorithm is
can be achieved by using result of smaller measured by different factors. For example,
sub-problem. write a program for a defined algorithm,
(iii) Dynamic algorithms uses Memoization. execute it by using any programming
.s

language, and measure the total time it


9. Write a pseudo code that defines Fibonacci takes to run.
Iterative algorithm with Dynamic
(iii) The execution time that you measure in this
programming approach.
w

case would depend on a number of factors


Ans. The following shows a simple Dynamic such as:
programming approach for the generation of ■ Speed of the machine
Fibonacci series.
■ Compiler and other system Software
w

Initialize f0=0, f1 =1 tools


Step 1 - Print the initial values of Fibonacci f0 ■ Operating System
and f1 ■ Programming language used
w

Step 2 - Calculate fibanocci fib ← f0 + f1 ■ Volume of data required


Step 3 - Assign f0← f1, f1← fib (iv) However, to determine how efficiently
Step 4 - Print the next consecutive value of an algorithm solves a given problem, you
fibanocci fib would like to determine how the execution
step 5 - Goto step-2 and repeat until the specified time is affected by the nature of the
number of terms generated algorithm.

42
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(v) Therefore, we need to develop fundamental 3. Explain the sorting algorithm that uses n-1
laws that determine the efficiency of a number passes to get the final sorted list.

Algorithmic strategies
program in terms of the nature of the
Ans. (i) Insertion sort is a simple sorting algorithm.
underlying algorithm.
It works by taking elements from the list
2. Differentiate Algorithm and program. one by one and inserting then in their

m
Ans. correct position in to a new sorted list.
Algorithm Program (ii) This algorithm builds the final sorted array
at the end. This algorithm uses n-1 number
Algorithm helps to solve Program is an

co
of passes to get the final sorted list as per the
a given problem logically expression of algorithm
and it can be contrasted in a programming pervious algorithm as we have discussed.
with the program language. Pseudo for Insertion sort :
Algorithm can be Algorithm can be Step 1 − If it is the first element, it is already
categorized based on implemented by

s.
sorted.
their implementation structured or object
methods, design oriented programming Step 2 − Pick next element
techniques etc approach
Step 3 − Compare with all elements in the sorted

ok
There is no specific rules Program should be sub-list
for algorithm writing but written for the selected
some guidelines should language with specific Step 4 − Shift all the elements in the sorted sub-
be followed. syntax list that is greater than the value to be
Algorithm resembles a Program is more sorted
o
pseudo code which can specific to a
Step 5 − Insert the value
be implemented in any programming language
ab

language Step 6 − Repeat until list is sorted


ur
.s
w
w
w

43
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

UNIT-II
 CORE PYTHON
 

m
Chapter

5
PYTHON-VARIABLES AND OPERATORS

co
CHAPTER SNAPSHOT
5.1 Introduction 5.7 Tokens

s.
5.2 Key features of Python 5.7.1. Identifiers
5.3 Programming in Python 5.7.2. Keywords
5.3.1 Interactive mode Programming 5.7.3 Operators

ok
5.3.2 Script mode Programming 5.7.4 Delimiters
5.4 Input and Output Functions 5.7.5 Literals
5.4.1 The print() function 5.8 Python Data types
5.4.2 input() function 5.8.1 Number Data type
5.8.2 Boolean Data type
o
5.5 Comments in Python
5.8.3 String Data type
5.6 Indentation
ab

Evaluation 4. Which of the following character is used to


give comments in Python Program? [PTA-6]
(a) # (b) & (c) @ (d) $
Part - I  [Ans. (a) #]
ur

Choose the best answer  (1 mark) 5. This symbol is used to print more than one
item on a single line.
1. Who developed Python? (a) Semicolon (;) (b) Dollor ($)
(a) Ritche (c) comma (,) (d) Colon (:)
.s

(b) Guido Van Rossum  [Ans. (c) comma (,)]


(c) Bill Gates 6. Which of the following is not a token?
(d) Sunder Pitchai (a) Interpreter (b) Identifiers
w

 [Ans. (b) Guido Van Rossum] (c) Keyword (d) Operators


 [Ans. (a) Interpreter]
2. The Python prompt indicates that Interpreter
7. Which of the following is not a Keyword in
is ready to accept instruction.
Python?
w

(a) >>> (b) <<< (a) break (b) while


(c) # (d) << (c) continue (d) operators
 [Ans. (a) >>>]  [Ans. (d) operators]
w

3. Which of the following shortcut is used to 8. Which operator is also called as Comparative
create new Python Program? operator? [PTA-1]
(a) Ctrl + C (b) Ctrl + F (a) Arithmetic (b) Relational
(c) Ctrl + B (d) Ctrl + N (c) Logical (d) Assignment
 [Ans. (d) Ctrl + N]  [Ans. (b) Relational]
[44]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


9. Which of the following is not Logical operator? 5. Write short notes on Exponent data?
(a) and (b) or Ans. An Exponent data contains decimal digit part,

Python - Variables and Operators


(c) not (d) Assignment decimal point, exponent part followed by one or
 [Ans. (d) Assignment] more digits.
10. Which operator is also called as Conditional Example: 12.E04, 24.e04.

m
operator?
(a) Ternary (b) Relational
Part - III
(c) Logical (d) Assignment Answer the following questions
 [Ans. (a) Ternary]  (3 marks)

co
Part - II 1. Write short notes on Arithmetic operator with
Answer the following questions examples.
Ans. (i) An arithmetic operator is a mathematical
 (2 marks)

s.
operator that takes two operands and
1. What are the different modes that can be used performs a calculation on them. They are
used for simple arithmetic.
to test Python Program?
(ii) Most computer languages contain a set

ok
Ans. (i) In Pyhton, programs can be written in two
of such operators that can be used within
namely Interactive mode and Script mode. equations to perform different types of
(ii) Interactive mode allows us to write codes sequential calculations.
in Python command prompt (>>>).
(iii) Python supports the following Arithmetic
(iii) Script mode is used to create and edit
operators.
o
python source file with the extension .py
Operator –
2. Write short notes on Tokens. [PTA-4; HY-2019] Examples Result
Operation
ab

Ans. Python breaks each logical line into a sequence


of elementary lexical components known as Assume a=100 and b=10. Evaluate the
Tokens. The normal token types are following expressions
(i) Identifiers, + (Addition) >>> a + b 110
(ii) Keywords, – (Subtraction) >>> a – b 90
ur

(iii) Operators, * (Multiplication) >>> a * b 1000


(iv) Delimiters and
/ (Division) >>> a / b 10.0
(v) Literals.
% (Modulus) >>> a % 30 10
.s

3. What are the different operators that can be


** (Exponent) >>> a ** 2 10000
used in Python? [PTA-5, 6]
// (Floor Division) >>> a //30 3
Ans. (i) Operators are special symbols which
(Integer
w

represent computations, conditional Division)


matching in programming.
(ii) The operators that can be used in Python. 2. What are the assignment operators that can be
used in Python?
w

4. What is a literal? Explain the types of literals?


Ans. Literal is a raw data given in a variable or Ans. (i) In Python, = is a simple assignment
constant. In Python, there are various types of operator to assign values to variable. Let a
literals. = 5 and b = 10 assigns the value 5 to a and
w

10 to b these two assignment statement can


(i) Numeric Literals consists of digits and are also be given as a,b=5,10 that assigns the
immutable. value 5 and 10 on the right to the variables
(ii) String literal is a sequence of characters a and b respectively.
surrounded by quotes.
(ii) There are various compound operators in
(iii) Boolean literal can have any of the two Python like +=, -=, *=, /=, %=, **= and //=
values : True or False. are also available.

45
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Operator Description Example
Assume x=10
Unit II - Chapter 5

= Assigns right side operands to left variable >>> x=10


>>> b="Computer"
+= Added and assign back the result to left operand i.e. x=30 >>> x+=20 #x=x+20

m
–= Subtracted and assign back the result to left operand i.e. x=25 >>> x–=5 # x=x–5
*= Multiplied and assign back the result to left operand i.e. x=125 >>> x*=5 # x=x*5

co
/= Divided and assign back the result to left operand i.e. x=62.5 >>> x/=2 # x=x/2
%= Taken modulus (Remainder) using two operands and assign the >>> x%=3 # x=x%3
result to left operand i.e. x=2.5
**= Performed exponential (power) calculation on operators and >>> X**=2 # x=x**2

s.
assign value to the left operand i.e. x=6.25
//= Performed floor division on operators and assign value to the left >>> x//=3
operand i.e. x=2.0

ok
3. Explain Ternary operator with examples. [PTA-1]
Ans. (i) Ternary operator is also known as conditional operator that evaluate something based on a condition
being true or false.
o
(ii) It simply allows testing a condition in a single line replacing the multiline if-else making the code
compact.
Syntax :
ab

Variable Name = [on_true] if [Test expression] else [on_false]


(iii) Example:
min = 50 if 49 < 50 else 70 // min = 50
ur

min = 50 if 49 > 50 else 70 // min = 70


4. Write short notes on Escape sequences with examples.
Ans. (i) In Python strings, the backslash "\" is a special character, also called the "escape" character.
.s

(ii) It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a
carriage return.
(iii) For example to print the message "It's raining", the Python command is
w

>>> print ("It\'s raining")


It's raining
w

Escape sequence character Description Example Output


\\ Backslash >>> print("\\test") \test
w

\* Single-quote >>> print("Doesn\'t") Doesn't

\" Double-quote >>> print("\"Python\"") "Python"

\n New line print("Python","\n", "Lang..") Python Lang..

\t Tab Print("Python", "\t","Lang..") Python Lang..

46
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5. What are string literals? Explain.

Python - Variables and Operators


Ans. (i) In Python, a string literal is a sequence of
characters surrounded by quotes. Python
supports single, double and triple quotes
for a string.

m
(ii) A character literal is a single character
surrounded by single or double quotes. The
value with triple-quote "' '" is used to give
multi-line string literal.

co
To test String Literals :
# Demo Program to test String Literals
strings = "This is Python"
(ii) Now, Save As dialog box appears on the

s.
char = "C" screen.
File Location
multiline_str = "'This is a multiline string
with more than one line code."'

ok
print (strings)
print (char)
print (multiline_str)
# End of the Program
o
Output:
This is Python
ab

C
This is a multiline string with more than
one line code. File Name (demo1)

Part - IV
ur

Answer the following questions Save As Dialog Box

(iii) In the Save As dialog box, select the


 (5 marks) location where you want to save your
Python code, and type the file name in File
.s

1. Describe in detail the procedure Script mode Name box. Python files are by default saved
programming.
with extension .py. Thus, while creating
Ans. A script is a text file containing the Python Python scripts using Python Script editor,
w

statements. Python Scripts are reusable code. no need to specify the file extension.
Once the script is created, it can be executed (iv) Finally, click Save button to save your
again and again without retyping. The Scripts Python script.
w

are editable. Executing Python Script :


Creating Scripts in Python : (i) Choose Run → Run Module or Press F5
(i) Choose File → New File or press Ctrl + N in
w

Python shell window.


a=100
(ii) An untitled blank script text editor will be
b=350
displayed on screen. c=a+b
print ("The Sum=", c)
(iii) Type the code in Script editor
Saving Python Script :
To Execute Python Script
(i)  Choose File → Save or Press Ctrl + S

47
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(ii) If code has any error, it will be shown in (viii) The input ( ) accepts all data as string
red color in the IDLE window, and Python or characters but not as numbers. If a
Unit II - Chapter 5

describes the type of error occurred. To numerical value is entered, the input values
correct the errors, go back to Script editor, should be explicitly converted into numeric
make corrections, save the file using Ctrl + S data type. The int( ) function is used to
or File → Save and execute it again. convert string data as integer data explicitly.

m
(iii) For all error free code, the output will
appear in the IDLE window of Python. (ix) Example 3 :
2. Explain input () and print () functions with x = int (input(“Enter Number 1: ”))
examples. [Govt. MQP-2019; PTA-3] y = int (input(“Enter Number 2: ”))

co
Ans. Input and Output Functions : A program print (“The sum = ”, x+y)
needs to interact with the user to accomplish the
desired task; this can be achieved using Input- Output :
Output functions. The input() function helps to Enter Number 1: 34
enter data at run time by the user and the output Enter Number 2: 56

s.
function print() is used to display the result of
the program on the screen after execution. The sum = 90
The input() function : The print() function :

ok
(i)  In Python, input( ) function is used to (i) In Python, the print() function is used to
accept data as input at run time. The syntax display result on the screen. The syntax for
for input() function is, print() is as follows :
Variable = input (“prompt string”) (ii) Example :
(ii)  Where, prompt string in the syntax is a
print (“string to be displayed as output ” )
o
statement or message to the user, to know
what input can be given. print (variable )
(ii) If a prompt string is used, it is displayed on print (“String to be displayed as output ”,
ab

the monitor; the user can provide expected variable)


data from the input device. The input( )
 print (“String1 ”, variable, “String 2”,
takes whatever is typed from the keyboard
and stores the entered data in the given  variable, “String 3” ……)
variable. (iii) Example :
ur

(iv) If prompt string is not given in input( ) no >>> print (“Welcome to Python
message is displayed on the screen, thus, Programming”)
the user will not know what is to be typed Welcome to Python Programming
as input.
>>> x = 5
.s

(v) Example 1 : input( ) with prompt string


>>> city=input (“Enter Your City: ”) >>> y = 6
Enter Your City: Madurai >>> z = x + y
>>> print (z)
w

>>> print (“I am from “, city)


I am from Madurai 11
(vi) Example 2 : input( ) without prompt string >>> print (“The sum = ”, z)
>>> city=input()
w

The sum = 11
Madurai
>>> print (“The sum of ”, x, “ and ”, y, “ is ”,
>>> print (I am from", city)
z)
I am from Madurai
The sum of 5 and 6 is 11
w

(vii) Note that in example-2, the input( ) is not


having any prompt string, thus the user will (iv) The print ( ) evaluates the expression before
not know what is to be typed as input. If printing it on the monitor.
the user inputs irrelevant data as given in (v) The print () displays an entire statement
the above example, then the output will which is specified within print ( ). Comma
be unexpected. So, to make your program (,) is used as a separator in print ( ) to print
more interactive, provide prompt string
with input( ). more than one item.

48
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Discuss in detail about Tokens in Python. Output :
 [PTA-3; QY-2019] The sum = 110

Python - Variables and Operators


Ans. Python breaks each logical line into a sequence The a>b = True
of elementary lexical components known as The a > b or a == b = True
Tokens. The normal token types are The a+=10 is = 110
(i) Identifiers,

m
(iv) Delimiters : Python uses the symbols
(ii) Keywords,
(iii) Operators,
and symbol combinations as delimiters in
(iv) Delimiters and expressions, lists, dictionaries and strings.
(v) Literals. Following are the delimiters.

co
(i) Identifiers : ( ) [ ] { }
■ An Identifier is a name used to identify a
variable, function, class, module or object. , : . ' = ;
■ An identifier must start with an alphabet += -= *= /= //= %=
(A..Z or a..z) or underscore ( _ ). &= |= ^= >>= <<= **=

s.
■ Identifiers may contain digits (0 .. 9).
■  Python identifiers are case sensitive i.e. (v) Literals : Literal is a raw data given in a
uppercase and lowercase letters are distinct. variable or constant. In Python, there are
■ Identifiers must not be a python keyword. various types of literals.

ok
■  Python does not allow punctuation ■  Numeric Literals consists of
character such as %,$, @ etc., within characters surrounded by quotes.
identifiers. ■ String literal is a sequence of
Example : characters surrounded by quotes.
Example of valid identifiers : Sum, total_
■ Boolean literal can have any of the
o
marks, regno, num1
Example of invalid identifiers : 12Name, two values : True or False.
name$, total-mark, continue PTA Questions and Answers
ab

(ii) Keywords :
■ Keywords are special words used by Python
interpreter to recognize the structure of 1 MARK
program.. 1. What will be the value of X from the following
■ As these words have specific meaning for
code snipped? [PTA-2]
ur

interpreter, they cannot be used for any


other purpose. A, B = 10, 3
■ Python keywards : false, class, If, elif, else, X = A if (A/B==3) else B
pass, break etc. print(X)
(iii) Operators :
.s

■ In computer programming languages (a) 3 (b) 10


operators are special symbols which (c) True (d) False
represent computations, conditional  [Ans. (d) False]
matching etc.
w

■ The value of an operator used is called 2. In how many ways programs can be written in
operands. Python? [PTA-3]
■ Operators are categorized as Arithmetic, (a) Two (b) Three
w

Relational, Logical, Assignment etc. Value


and variables when used with operator are (c) Four (d) Five
known as operands.  [Ans. (a) Two]
Example :
w

a=100 3. Which of the following is the valid Python


b=10 program file name? [PTA-3]
print (“The sum = ”,a+b) (a) pycpp.py
print ("The a > b =", a>b) (b) pycpp.cpp
print ("The a > b or a == b =", a > b or
a==b) (c) pycpp.c
a+=10 (d) pycpp.js [Ans. (a) pycpp.py]
print("The a+=10 is =", a)
49
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. Which of the following statement(s) is not 5 MARKS
correct? [PTA-4]
1. Explain the different operators in Python.
Unit II - Chapter 5

(1) Python is a general purpose programming


 [PTA-1; HY-2019]
language which can be used for both
Ans. In computer programming languages
scientific and non-scientific programming. operators are special symbols which represent

m
(2) Python is a platform independent computations, conditional matching etc. The
programming language. value of an operator used is called operands.
(3) The prorams written in Python are difficult Operators are categorized as Arithmetic,
to read and understand. Relational, Logical, Assignment etc. Value and

co
variables when used with operator are known as
(a) Statement (1) Only
operands.
(b) Statement (1) and (2)
(i) Arithmetic operators :
(c) Statement (3) Only
 An arithmetic operator is a mathematical
(d) All statements

s.
operator that takes two operands and per-
 [Ans. (c) Statement (3) Only] forms a calculation on them. They are used
5. The floor division operator in Python: [PTA-5] for simple arithmetic. Most computer lan-
(a) / (b) % (c) %% (d) // guages contain a set of such operators that

ok
 [Ans. (d) //] can be used within equations to perform
different types of sequential calculations.
2 MARKS
(ii) Relational or Comparative operators :
1. What are keywords in Python? [PTA-1]   A Relational operator is also called as
o
Ans. Comparative operator which checks the
false class finally Is return relationship between two operands. If the
relation is true, it returns True; otherwise
ab

none continue For Lambda try it returns False.


3. What are the key features of Python? [PTA-3] (iii) Logical operators :
Ans. (i)  It is a general purpose programming In python, Logical operators are used to
language which can be used for both perform logical operations on the given
ur

scientific and non-scientific programming. relational expressions. There are three log-
ical operators they are and, or and not.
(ii) It is a platform independent programming
(iv) Assignment operators :
language.
 In Python, = is a simple assignment
.s

(iii) The programs written in Python are easily


operator to assign values to variable. Let a
readable and understandable. = 5 and b = 10 assigns the value 5 to a and
3 MARKS 10 to b these two assignment statement
w

can also be given as a,b=5,10 that assigns


1. What are the rules to be followed while the value 5 and 10 on the right to the
creating an identifier in Python? [PTA-2] variables a and b respectively. There are
various compound operators in Python
w

Ans. (i) An identifier must start with an alphabet


(A..Z or a..z) or underscore ( _ ).. like +=, -=, *=, /=, %=, **= and //= are also
available.
(ii) Identifiers may contain digits (0 .. 9).
(v) Conditional operator :
w

(iii) 
Python identifiers are case sensitive i.e.
Ternary operator is also known as condi-
uppercase and lowercase letters are distinct.
tional operator that evaluate something
(iv) Identifiers must not be a python keyword. based on a condition being true or false.
(v)  Python does not allow punctuation It simply allows testing a condition in a
character such as %,$, @ etc., within single line replacing the multiline if-else
identifiers. making the code compact.

50
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. In Python, the script mode programs can be
Government Exam Questions and Answers
stored with the extension.

Python - Variables and Operators


1 MARK (a) .pyt (b) .pyh
(c) .py (d) .pon
1. Extension of Python files is [Govt. MQP-2019]  [Ans. (c) .py]
(a) .Pyt (b) .txt 4. Which of the following mode cannot be

m
(c) .Odm (d) .Py written Python program?
[Ans. (d) .Py] (i) Interactive mode (ii) Script mode
2. How many ways python program can be (iii) Calculator mode (iv) Executable mode

co
written? [QY-2019] (a) i (b) ii
(a) 2 (b) 2 (c) 3 (d) 1 (c) i and iii (d) iii and iv
[Ans. (a) 2]  [Ans. (d) iii and iv]
3. _______ separation is necessary between 5. Which of the following defines the Python
interactive mode of programming?

s.
tokens. [QY-2019]
(a) ; (b) Dellimiter (a) >>> (b) <<<
(c) >> (d) <<
(c) WhiteSpace (d) :
 [Ans. (a) >>>]

ok
[Ans. (c) WhiteSpace]
6. Which of the following mode allows to write
2 MARKS codes in Python command prompt?
(a) Script mode (b) Complier mode
1. Define Operator and Operand.
(c) Interactive mode (d) Program mode
 [Govt. MQP-2019]
o
 [Ans. (c) Interactive mode]
Ans. (i) Operators are categorized as Arithmetic,
Relational, Logical, Assignment etc. Value 7. Which mode can also be used as a simple
calculator in Python?
ab

and variables when used with operator are


known as operands. (a) Information (b) Intelligent
(ii) Arithmetic operators : (c) Script (d) Interactive
An arithmetic operator is a mathematical  [Ans. (d) Interactive]
operator that takes two operands and per- 8. Which mode displays the python code result
ur

forms a calculation on them. They are used immediately?


for simple arithmetic. Most computer lan- (a) Compiler (b) Interactive
guages contain a set of such operators that (c) Script (d) Program
can be used within equations to perform  [Ans. (b) Interactive]
.s

different types of sequential calculations. 9. Which of the following used to develop and
run Python code?
additional questions and Answers (a) GUI
w

(b) Command prompt


Choose the Correct Answer 1 MARK (c) IDLE (d) CUI
1. Python language was released in  [Ans. (c) IDLE]
(a) 1992 (b) 1991
w

10. Which mode can also be used as a simple


(c) 1994 (d) 2001 calculator?
 [Ans. (b)1991] (a) Calc mode (b) Interactive mode
2. IDLE expansion is (c) Script mode (d) Code mode
w

(a) Integrated Development Learning Environment  [Ans. (b) Interactive mode]


(b) Information Development Logical Environment 11. Which of the following indicates in Python
(c) Integrated Development Language Environment that interpreter is ready to accept instructions?
(d) Interactive Development Learning Environment (a) >>> (b) <<<
(c) .py (d) <<
 [Ans. (a) Integrated Development Learning
Environment]  [Ans. (a) >>>]

51
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


12. >>> indicates that 21. Which of the following can be identify by an
(a) IDLE is working in script mode identifier?
Unit II - Chapter 5

(b) Source program can be created and stored (a) variable (b) function
(c) IDLE is working in Interactive mode (c) class (d) all of these
(d) It will not display the results immediately  [Ans. (d) all of these]
[Ans. (c) IDEL is working in Interactive 22. If a = 100, then the expression a**2 output is

m

mode] (a) 1000 (b) 10000
13. Which of the following command is used to (c) 200 (d) 400
execute Python script?  [Ans. (b) 10000]

co
(a) Run → Python Module 23. If a = 100, then the expression a//30 is
(b) File → Run Module (a) 10.0 (b) 0.10
(c) Run → Run Module (c) 3 (d) 3.0
(d) Run → Module Fun  [Ans. (c) 3]
 [Ans. (c) Run → Run Module] 24. Which of the following operator checks the

s.
14. Which function helps to enter data at run time relationship between two operands?
by the user? (a) Arithmetic (b) Comparative
(a) input ( ) (b) read ( ) (c) Assignment (d) Conditional

ok
(c) get ( ) (d) Pyinput ( )  [Ans. (b) Comparative]
 [Ans. (a) input ( )] 25. How may logical operators in Python?
15. From the following statement absence of which (a) 2 (b) 4 (c) 5 (d) 3
one no message is displayed on the screen?  [Ans. (d) 3]
variable = input ("prompt string") 26. Which operator replaces multiline if-else in
o
(a) Variable (b) input Python?
(a) Conditional (b) Logical
(c) "prompt string" (d) " "
(c) Relational (d) Assignment
ab

 [Ans. (c) "prompt string"]


 [Ans. (a) Conditional]
16. Which of the following function in Python is 27. In Python, the delimiters are not used in
used to convert strings data as integer data (a) Expressions (b) functions
explicitly? (c) dictioncuries (d) strings
(a) integer ( ) (b) num ( )  [Ans. (b) functions]
ur

(c) int ( ) (d) number ( ) 28. Which of the following is a raw data given in a
 [Ans. (c) int ( )] variable or constant?
17. Multiline comments in Python enclosed with (a) Information (b) Delimiters
(a) # # (b) < > (c) Literal (d) Keywords
.s

(c) ! ! (d) $ $  [Ans. (c) Literal]


 [Ans. (a) # #] 29. Which of the following is not a type of literal?
18. A sequence of elementary lexical components (a) Numeric (b) Expression
w

of Python statement is known as (c) String (d) Boolean


 [Ans. (b) Expression]
(a) Keywords (b) Tokens
30. What is the output for the following
(c) Delimiters (d) Literals
m = 25 if 24 < 25 else 50
w

 [Ans. (b) Tokens] (a) 25 (b) 50 (c) 24<25 (d) 0


19. Which of the following is not a type of token?  [Ans. (a) 25]
31. Which literal are immutable?
(a) Identifier (b) Keywords
(a) Integer (b) Float
w

(c) Literals (d) functions


(c) Complex (d) All of these
 [Ans. (d) functions]
 [Ans. (d) All of these]
20. Which of the following can not be identify by 32. Which of the following is not a numerical
an identifier literal type?
(a) constant (b) variable (a) Integer (b) Float
(c) function (d) class (c) Boolean (d) Complex
 [Ans. (a) constant]  [Ans. (c) Boolean]

52
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


33. Which of the following is a sequence of Match the following
characters surrounded by quotes? List I List II

Python - Variables and Operators


1.
(a) String (b) Complex
i) 0b1010 1) Hexadecimal Literal
(c) Boolean (d) Octal
 [Ans. (a) String] ii) 100 2) Octal Literal
34. The multipleline string literal given in iii) Oo310 3) Decimal Literal

m
(a) ' ' (b) " " iv) Ox12c 4) Binary Literal
(c) # # (d) "" ""
 [Ans. (d) "" ""] (i) (ii) (iii) (iv)
(a) 1 2 3 4

co
35. Which of the following characters is also called
the "escape" character? (b) 1 3 2 4
(c) 4 2 3 1
(a) \ (b) / (c) # (d) =
(d) 4 3 2 1
 [Ans. (a) \]
 [Ans. (d) (i)-4; (ii)-3; (iii)-2; (iv)-1]
36. Which of the following is not a fundamental

s.
data type? 2. List I List II
(a) tuples (b) lists i) 567 1) Long Integer
(c) character (d) dictionaries
ii) 0432 2) Decimal Integer

ok
 [Ans. (c) character]
iii) 53L 3) Hexdecimal Integer
37. A built-in number datatype supports.
(a) integers iv) Ox562 4) Octal Integer
(b) floating point numbers (i) (ii) (iii) (iv)
(c) Complex umbers (d) all of these
o
(a) 2 4 1 3
 [Ans. (d) all of these] (b) 2 1 4 3
38. Which of the following character is used to
(c) 2 3 4 1
ab

denote long integer?


(d) 4 2 1 3
(a) N (b) LO (c) L (d) D
 [Ans. (c) L]  [Ans. (a) (i)-2; (ii)-4; (iii)-1; (iv)-3]
39. Which of the following date includes decimal Choose the odd man out
point?
ur

1. (a) IDE (b) GUI


(a) Character (b) String
(c) IDLE (d) CWI[Ans. (d) CWI]
(c) Boolean (d) Floating point
Reason : It is a National Research Institute for
 [Ans. (d) Floating point]
mathematics and computer science in
.s

40. Exponent data example is


Netherlands.
(a) 123.45 (b) .0537
(c) 2.4E–2 (d) Ox5 2. (a) < > (b) <<<
 [Ans. (c) 2.4E–2]
w

(c) < (d) >>> [Ans. (d) >>>]


41. How many floating point values needed to
Reason : It is a Python command prompt.
represent complex number?
(a) 2 (b) 3 (c) 1 (d) 0 3. (a) Identifiers (b) Operators
w

 [Ans. (a) 2] (c) Literals (d) Tokens


42. A boolean data type have the values  [Ans. (d) Tokens]
(a) 0 or 1 (b) L or O Reason : The other options are the types of tokens.
w

(c) O or Ox (d) t r u e o r f a l s e
4. (a) Pass (b) Fail
 [Ans. (d) true or false]
(c) Raise (d) elif [Ans. (b) Fail]
43. Which data can be enclosed with Single or
Double or Triple quotes? 5. (a) and (b) or
(a) Boolean (b) String (c) not equal to (d) not
(c) Exponent (d) n o n e o f t h e s e  [Ans. (c) not equal to]
 [Ans. (b) String]
53
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


6. (a) + = (b) //= 9. What must be entered in ________ from the
(c) /– (d) %= following statement to accept the value entered
Unit II - Chapter 5

(e) = = [Ans. (e) = =] as integer?


X = ______ input ("Enter number")
7. (a) ' ' (b) " " (a) integer (b) int
(c) ''' ''' (d) "" "" (c) number (d) numeric

m
 [Ans. (d) "" ""]  [Ans. (b) int]

Choose and fill in the blanks 10. The inputs ( ) accepts all data as ______ or
__________.
1. ________ mode is used to create and edit

co
(a) String or characters
python source file.
(b) String or numbers
(a) Script (b) Interactive (c) Characters or numbers
(c) Informative (d) Source (d) integers or exponent
 [Ans. (a) Script]  [Ans. (a) String or characters]

s.
2. The __________ command is used to open 11. In Python, comments begin with _______.
Python shell window. (a) / (b) # (c) \ (d) //
(a) File → File New (b) File → New  [Ans. (b) #]

ok
(c) File → New File (d) File → File Open 12. The _________ statements are ignored by the
 [Ans. (c) File → New File] Python interpreter.
(a) input ( ) (b) print ( )
3. In Python Script Editor, the errors will be
(c) int ( ) (d) comments
shown in _________ color in the IDLE window.
o
 [Ans. (d) comments]
(a) red (b) green
(c) blue (d) orange 13. Python uses _____ and ______ to define
ab

program blocks.
 [Ans. (a) red] (a) Alt, Shift (b) Spaces, tabs
4. Press ________ to execute Python Script. (c) tabs, functions (d) Ctrl, Shift
(a) F2 (b) F3 (c) F4 (d) F5  [Ans. (b) Spaces, tabs]
 [Ans. (d) F5] 14. In Python, there are _____ normal token types.
ur

(a) 4 (b) 3 (c) 5 (d) 7


5. The input ( ) function helps to enter data at  [Ans. (c) 5]
________ by the user.
(a) compile time (b) linking time 15. In computer programming languages
.s

________are special symbols which represent


(c) run time (d) module time computations.
 [Ans. (c) run time] (a) keywords (b) literals
(c) delimiters (d) operators
w

6. The output function _______ is used to display


the result of the Python Program.  [Ans. (d) operators]
(a) out ( ) (b) write ( ) 16. Value and variables when used in operator are
known as ________.
w

(c) print ( ) (d) execute ( )


 [Ans. (c) print ( )] (a) Operands (b) Keywords
(c) Identifiers (d) f u n c t i o n s
7. >>> print ("A = ", a _____ "B=", b).  [Ans. (a) Operands]
w

(a) : (b) , (c) ; (d) :: 17. _________ and __________ when used with
 [Ans. (b) ,] operator are called operands.
(a) Keywords, identifiers
8. _______ = input ("Prompt string").
(b) Literals, delimiters
(a) variable (b) integer (c) Value, Variables
(c) keyword (d) operator (d) Literals, Keywords
 [Ans. (a) variable]  [Ans. (c) Value, Variables]
54
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


18. In Python ________ is a simple assignment (a) i and ii (b) ii and iii
operator. (c) ii and iv (d) i, ii, iv

Python - Variables and Operators


(a) = (b) != (c) = = (d) #  [Ans. (c) ii and iv]
 [Ans. (a) =]
2. (i) Python created by Guido Van Rossum.
19. Python uses the symbols and symbol (ii) Python shell can be used in two ways.
combinations as ________ in expressions.

m
(iii) Python used whitespace to define blocks
(a) literals (b) keywords (iv) Whitespace separation is necessary between
(c) identifiers (d) delimiters tokens, identifiers or keywords.
 [Ans. (d) delimiters]
(a) i and ii (b) ii, iii and iv

co
20. Numeric literals can belong to ________ (c) i, ii and iv (d) i, ii and iii
different numerical types.
(a) 4 (b) 3 (c) 2 (d) 5 (e) all of these [Ans. (e) all of these]
 [Ans. (b) 3] 3. Which of the following is the correct statement

s.
21. The ______ escape sequence character in Python?
description is new line. (a) print ('string to be displayed as output ')
(a) \t (b) \l (c) \n (d) \h (b) print (a) ;
 [Ans. (c) \n]

ok
(c) print (" T sum = ", a)
22. All data values in Python are _______. (d) print ("X=", x, "Y = ",y) ;
(a) objects (b) class  [Ans. (c) print ("T sum = ", a)]
(c) type (d) functions
 [Ans. (a) objects] Choose the correct Pair
o
23. ________ data can be decimal, octal or 1. (a) File → File to open Python
hexadecimal. New Interactive mode
ab

(a) Character (b) Integer (b) File → File to work with Python Script
(c) Escape sequence (d) Symbols New Mode
 [Ans. (b) Integer] (c) F5 to modify the python script
24. Octal integer use _____ to denote octal digits. (d) >>> is a python script mode
ur

(a) O (b) Ox (c) 8 (d) Oc prompt


 [Ans. (a) O]  [Ans. (b) File → File New – to work with
25. ________ is to denote hexadecimal integer.  Python Script Mode]
(a) 16 (b) Ox
.s

2. Choose the correct pair from the following if


(c) Ox (d) b or c
a = 100 and b = 45.
 [Ans. (d) b or c]
(a) a = = b – false (b) a > b – false
26. Complex number is made up of two _______
w

(c) a < b – false (d) a ! = b – false


values.
 [Ans. (a) a = = b – false]
(a) Integer (b) String
(c) floating point (d) octal 3. (a) Octal literal – Ob1010
w

 [Ans. (c) floating point] (b) Hexadecimal literal – 0100


Choose the correct statement (c) Complex literal – 3+5.6j
1. (i) In Python, programs can be written in many (d) Binary literal – Oo310
w

ways.  [Ans. (c) Complex literal – 3+5.6j]


(ii) Interactive mode and script mode are the 4. (a) O102 – hexadecimal integer
modes used to write programs in Python. (b) Ox432 – Octal Integer
(iii) Python command prompt is <<< (c) 2EO – Exponent data
(iv) In Python, interactive mode displays the (d) 12.45 – Integer data
result immediately and also used as a
calculator.  [Ans. (c) 2EO – Exponent data]

55
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose the incorrect statement Choose the incorrect Pair
1. (i) P  ython script is a file that contains python
Unit II - Chapter 5

1. (i) Ctrl + N to create a new python


statements script
(ii) Python script are not reusable code
(ii) Ctrl + S to save the python script
(iii) Python scripts can be executed many times
(iii) F5 to modify the python

m
without retyping
(iv) Python scripts are editable script
(a) i only (b) ii only (iv) Run → Run to excuse the python
(c) iii only (d) i and iv Module script

co
 [Ans. (b) ii only] (a) i, ii, iii (b) i and ii
2. (i) Python script is a file that contains python (c) ii, iii, iv (d) ii and iii
statements  [Ans. (d) ii and iii]
(ii) Python script are not reusable code 2. (a) 100 / 10 – 10.0

s.
(iii) Python scripts cannot be executed again and (b) 100 % 30 – 10
again without retyping
(c) 100 // 30 – 10.0
(iv) Python scripts are editable.
(d) 100 *×2 – 10000

ok
(a) i and ii (b) iii and iv
 [Ans. (c) 100 // 30 – 10.0]
(c) i and iii (d) ii and iii
 [Ans. (d) ii and iii] 3. Choose the incorrect pair from the following
3. (i) The input ( ) accepts all types of data (string, if a = 100 and b = 45.
characters, numbers) (a) a = = b – false
o
(ii) Python uses whitespace to define program (b) a ! = b – false
blocks (c) a > = b – True
ab

(iii) Comments in python begin with # (d) a < b – false [Ans. (b) a! = b – false]
(iv) Python uses { } to define program blocks
4. (a) Literal Numeric, string, Boolean
(a) i and iv (b) i, iii and iv
(c) ii and iv (d) ii and iii (b) Delimiters S ymbols and symbol
 [Ans. (a) i and iv] combinations
ur

4. (i) Python identifiers must start with an alphabet (c) Escape \t, \\, \n
(ii) Python identifiers many contain digits sequences
(iii) Python identifiers are not case sensitive (d) Conditional also known as operands
operator operator
.s

(iv) Python allows %,$@ characters with in


identifiers.  [Ans. (d) Conditional operator – also known
(a) i, ii (b) ii, iii  as operands operator]
w

(c) iii, iv (d) ii, iv 5. (a) x = y (b) x = 'y'


 [Ans. (c) iii, iv] (c) x = "y" (d) x = '''y'''
5. (i)  Tuples, lists and dictionaries are not  [Ans. (d) x = '''y''']
w

fundamental data types 6. (a) print ("Doesn\'t") Doesn't


(ii) Python uses spaces and tabs to define (b) print ("\" Python \" ") "Python"
program blocks
(c)
w

print ("Python", "\t", Python Lang


(iii) String data is denoted by O or Ox "lang..")
(iv) Complex number is made up of two integer (d) print ("Python", "\n", Python Lang...
values "Lang..")
(a) i, ii, iii (b) i, ii
(c) ii, iii, iv (d) i, iii, iv [Ans. (d) print ("Python", "\n",  "Lang..")
 [Ans. (d) i, iii, iv]  – Python Lang..]

56
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


7. (a) 102 – Decimal Integer 8. How will you display more than one item in
(b) 0789 – Octal Integer print ( )?

Python - Variables and Operators


(c) Ox 102 – hexadecimal Integer Ans. Comma (,) is used as a separator in print ( ) to
print more than one item.
(d) 342 – Long Integer
9. Write the syntax of input ( ) used in python.
 [Ans. (b) 0789 – Octal Integer]

m
Ans. Variable = input ("prompt string")
Very Short Answers 2 MARKS Where, prompt string in the syntax is a
1. How will you develop and run Python code? statement or message to the user, to know what
Ans. The version 3.x of Python IDLE (Integrated input can be given.

co
Development Learning Environment) is used to 10. Name the tokens where the whitespace in
develop and run Python code.
necessary in python.
2. How many ways the Python shell can be used? Ans. Whitespace separation is necessary between
Ans. Python shell can be used in two ways, viz., tokens, identifiers or keywords.

s.
Interactive mode and Script mode.
11. Why the following identifiers are invalid?
3. How the interactive mode of Python shell can
(i) 12 Name (ii) name$
be used as simple calculator? (iii) physics–mark (iv) break

ok
Ans. In interactive mode Python code can be directly
typed and the interpreter displays the result(s) Ans. (i) An identifies must start with an alphabet.
immediately. The interactive mode can also be (ii) No punctuation characters are allowed.
used as a simple calculator. (iii) Only underscore (–) allowed.
4. How will you invoke python IDLE? (iv) Identifiers must not be a Python keyword.
o
Ans. (i) The following command can be used to 12. Find the odd man out? Give reason.
invoke Python IDLE from Window OS. (i) sum = 100 (ii) regno = 12401
ab

(ii) Start → All Programs → Python 3.x → IDLE (iii) name = "Kannan"
(Python 3.x)
(iv) name = "Kumar"
(Or)
Ans. (iv) name = "Kumar"
(iii) Click python Icon on the Desktop if Reason : No function character allowed within
ur

available. identifiers.
5. How will you know the python IDLE working 13. Write a note on relational or comparative
in interactive mode? operator.
Ans. A Relational operator is also called as
.s

Ans. The prompt (>>>) indicates that Interpreter


is ready to accept instructions. Therefore, the Comparative operator which checks the
prompt on screen means IDLE is working in relationship between two operands. If the
interactive mode. relation is true, it returns True; otherwise it
returns False.
w

6. What is the purpose of using input : output


14. Assume the value of a = 100 and b = 75.
functions? Evaluate the following expression.
Ans. The input() function helps to enter data at run
w

(i) a==b (ii) a!=b (iii) a//b


time by the user and the output function print()
(iv) a>=b
is used to display the result of the program on
the screen after execution. Ans. (i) False (ii) true
(iii) 1 (iv) true.
w

7. Write the Syntax of using print () in python.


15. What are the uses of logical operator? Name
Ans. Syntax :
print (“string to be displayed as output ” ) the operators.
Ans. In python, Logical operators are used to perform
print (variable )
logical operations on the given relational
print (“String to be displayed as output ”, variable) expressions. There are three logical operators
print (“String1 ”, variable, “String 2”, variable, they are and, or and not.
 “String 3” ……)

57
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


16. Assume a = 50 and b = 40. Write the output the 3. Fill up the blanks to get the following output
following statement. from Python code given.
Unit II - Chapter 5

(i) print ("The a > b or a == b = ",a>b or a==b) Output :


(ii) print ("The a > b and a == b = ",a>b and Enter Number 1 : 34
a==b) Enter Number 2 : 70
(iii) print ("The not a > b = ",not a>b)

m
The Sum = 104
Ans. (i) The a > b or a == b = True Code :
(ii) The a > b and a == b = False
(iii) The not a > b = False. X = (1) (input ("Enter Number 1 :"))

co
Y = (2) ( (3) ("Enter Number 2 : "))
17. Write the output for the following code.
(4) ("The sum = ", (5) )
x,y = 50,150
Z = x if x>y else y Ans. (1) int (2) int (3) input (4) print (5) x + y
print ("Z is", Z) 4. Why the following statement not accept the

s.
Ans. Z is 150. data as numbers? Give reason and also state
18. Name the types of Numeric literals in python. what function is used to accept the number.
Ans. Numeric literals can belong to 3 different Ans. x = input ("Enter number")

ok
numerical types Integer, Float and Complex. Reason : If a numerical value is entered, the
19. Write the description of the following Escape input values should be explicitly converted into
sequence character. numeric data type. The int( ) function is used to
(i) \n (ii) \t convert string data as integer data explicitly.
o
Ans. (i) New line
5. Write a Python programme to get the following
(ii) Tab
output.
ab

20. Name the built – in number objects in python.


Output :
Ans. The built-in number objects in Python supports
integers, floating point numbers and complex Enter Number 1 : 50
numbers. Enter Number 2 : 50
21. What are keywords? X = 50 Y = 50
ur

Ans. Keywords are special words that are used by Ans. x,y=int (input("Enter Number 1 :")),
Python interpreter to recognize the structure of int (input ("Enter Number 2:"))
program. print ("X = ",x," Y = ",y)
Short Answers 3 MARKS Output :
.s

Enter Number 1 :30


1. Write the function of the following Enter Number 2:50
(i) Ctrl + N (ii) Ctrl + S (iii) F5 X = 30 Y = 50
w

Ans. (i) to open Python shell window. 6. Write a Python program to get the following
(ii) to save the Python file.
output.
(iii) to run the Python program.
w

Output :
2. Fill in the blanks
Enter Number 1 : 50
>>>city = (1) ("Enter your City")
Enter Number 2 : 50
Enter your city : (2)
w

The sum of 50 and 50 is 100


>>> print ("I am from", (3) )
Ans. x = int(input ("Enter Number 1")
I am from Chennai.
y = int(input("Enter Number 2")
Ans. (1) input (2) Chennai (3) City.
print ("The sum of ", x, "and", y, "is", x+y)

58
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


7. Write a short note on comment statement. 11. Identify the type of literals.
(i) OX13B (ii) i+34j (iii) 12e05

Python - Variables and Operators


(or)
Write a note on statement which are ignored (iv) 0346
by the Python interpreter. Ans. (i) Hexadecimal literal
Ans. (i) In Python, comments begin with hash (ii) Complex literal

m
symbol (#). The lines that begins with # are
considered as comments and ignored by (iii) Floating point literal
the Python interpreter. (iv) Octal literal.
(ii) Comments may be single line or no multi-

co
lines. The multiline comments should be 12. How will you represent Octal, hexadecimal
enclosed within a set of # as given below. and long integer data?
# It is Single line Comment Ans. Integer Data can be decimal, octal or hexadecimal.
# It is multiline comment Octal integer use O (both upper and lower case)
which contains more than one line # to denote octal digits and hexadecimal integer

s.
use OX (both upper and lower case) and L (only
8. How will you define program blocks in python? upper case) to denote long integer.
Ans. (i) Python uses whitespace such as spaces Long Answers 5 MARKS

ok
and tabs to define program blocks whereas
other languages like C, C++, java use curly 1. Write the output for the following python
braces { } to indicate blocks of codes for code.
class, functions or body of the loops and
block of selection command. x=10
x+=20
o
(ii) The number of whitespaces (spaces and
tabs) in the indentation is not fixed, but print ("The x += 20 is =",x)
all statements within the block must be x-=5
ab

indented with same amount spaces. print ("The x -= 5 is = ",x)


9. Fill in the blanks x*=5
(i) __________ statements are ignored by print ("The x *= 5 is = ",x)
Python interpreter. x/=2
ur

(ii) The value of an operator used is called print ("The x /= 2 is = ",x)


__________. x%=3
print ("The x %= 3 is = ",x)
(iii) 100//30 = _______.
.s

x**=2
Ans. (i) Comment
print ("The x **= 2 is = ",x)
(ii) Operands
x//=3
(iii) 3
w

print ("The x //= 3 is = ",x)


10. Assume a = 1000 b = 10, Evaluate the following Ans. Output :
expression. Type a Value for X : 10
The x += 20 is = 30
w

(i) a%30 (ii) a/b (iii) b**2 (iv) b//3 The x -= 5 is = 25


Ans. (i) 100 The x *= 5 is = 125
(ii) 100.0 The x /= 2 is = 62.5
w

The x %= 3 is = 2.5
(iii) 100
The x **= 2 is = 6.25
(iv) 3 The x //= 3 is = 2.0


59
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

  
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

 

6
Chapter
CONTROL STRUCTURES

m
CHAPTER SNAPSHOT

co
6.1 Introduction 6.2.2 Alternative or Branching Statement
6.2 Control Structures 6.2.3. Iteration or Looping constructs
6.2.1 Sequential Statement 6.2.4 Jump Statements in Python

Evaluation

s.
7. What is the output of the following snippet?
i=1
while True:
Part - I if i%3 ==0:

ok
break
Choose the best answer  (1 mark) print(i,end='')
1. How many important control structures are i +=1
there in Python? (a) 12 (b) 123 (c) 1234 (d) 124
(a) 3 (b) 4 (c) 5 (d) 6  [Ans. (a) 12]
o
 [Ans. (a) 3] 8. What is the output of the following snippet?
2. elif can be considered to be abbreviation of T=1
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 programming? (c) 0 (d) 1
 [Ans. (b) True]
ur

(a) Statements (b) Control


9. Which amongst this is not a jump statement ?
(c) Structure (d) Indentation (a) for (b) pass
 [Ans. (d) Indentation] (c) continue (d) break
4. Which statement is generally used as a  [Ans. (a) for]
.s

placeholder? 10. Which punctuation should be used in the


(a) continue (b) break blank?
(c) pass (d) goto if <condition>_
statements-block 1
w

 [Ans. (c) pass]


else:
5. The condition in the if statement should be in statements-block 2
the form of (a) ; (b) : (c) :: (d) !
w

(a) Arithmetic or Relational expression [Ans. (b) :]


(b) Arithmetic or Logical expression Part - II
(c) Relational or Logical expression Answer the following questions
w

(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? Ans. There are three important control structures are,
(a) do..while (b) while (ii) Sequential
(c) for (d) if..elif (ii) Alternative or Branching
 [Ans. (c) for] (iii) Iterative or Looping
[60]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Write note on break statement. (iii) Syntax:
Ans. The break statement terminates the loop if <condition>:

Control Structures
containing it. Control of the program flows to statements-block 1
the statement immediately after the body of the else:
loop. statements-block 2

m
3. Write is the syntax of if..else statement 3. Using if..else..elif statement write a suitable
Ans. Syntax : program to display largest of 3 numbers.
Ans. Code :
if <condition>:
n1=int(input(:Enter the first number:"))
statements-block 1

co
n2=int(input("Enter the second number:"))
else:
n3=int(input(:Enter the third number:"))
statements-block 2
if(n1?=n2)and(n1>=n3):
4. Define control structure. [PTA-2] biggest=n1;

s.
Ans. A program statement that causes a jump of elif(n2>=n1)and (n2>=n3):
control from one part of the program to another biggest=n2
is called control structure or control statement. else:

ok
5. Write note on range () in loop. [PTA-2] 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)
range (start,stop,[step]) Output :
Where, Enter the first number:1
o
start – refers to the initial value Enter the second number:3
stop – refers to the final value Enter the third number:5
ab

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

while <condition>:
 (3 marks) statements block 1
1. Write a program to display [PTA-5] [else:
statements block2]
A
.s

AB 5. List the differences between break and


ABC continue statements. [HY-2019]
ABCD
w

Ans. Break Continue


ABCDE
The break statement The continue
Ans. for i in range (1, 6):
terminates the loop statement is used to
for j in range (65, 65 + i)
w

containing it. skip the remaining


a=chr(j) part of a loop.
print
Control of the Control of the
w

2. Write note on if..else structure. program flows program flows start


Ans. (i) The if.. else statement provides control to to the statement with next iteration.
check the true block as well as the false immediately after the
block. body of the loop.
(ii) if..else statement thus provides two
possibilities and the condition determines Syntax : break Syntax : continue
which BLOCK is to be executed.

61
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Part - IV for each item
Unit II - Chapter 6

Answer the following questions in sequence


 (5 marks)
1. Write a detail note on for loop.

m
Yes
 [Govt. MQP-2019] Last item
Ans. (i) for loop : for loop is the most comfortable
reached?
loop. It is also an entry check loop. The

co
condition is checked in the beginning and
the body of the loop(statements-block 1)
is executed if it is only True otherwise the No
loop is not executed.
Body of for

s.
(ii) Syntax:
for counter_variable in sequence:
statements-block 1 Exit loop

ok
[else: # optional block for loop execution
statements-block 2]
Example :
(iii) The counter_variable mentioned in the
syntax is similar to the control variable #Program to illustrate the use of for loop - to
that we used in the for loop of C++ and print single digit even number
o
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
(iv) The syntax of range() is as follows: with suitable example. [HY-2019]
ur

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 :
optional part. if <condition-1>:
w

Examples for range() : statements-block 1


range (1,30,1) - will start the range of values
elif <condition-2>:
from 1 and end at 29
statements-block 2
w

range (2,30,2) - will start the range of values else:


from 2 and end at 28
statements-block n
range (30,3,-3) - will start the range of values
(iii) In the syntax of if..elif..else mentioned
w

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)
62
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Output 2 :
Enter mark in second subject : 73

Control Structures
Test false
Expression
of if Grade : B
3. Write a program to display all 3 digit odd
numbers.

m
True Test false
Expression
Body of if of elif Ans. for a in range (100, 1000):
True if a %2==1:
print b

co
Body of elif
Body of else
Output :
101, 103, 105, 107 ... .... 997, 999
if..elif..else statement execution
4. Write a program to display multiplication

s.
(iv) 'elif' clause combines if..else-if..else table for a given number.
statements to one if..elif…else. 'elif' can Ans. Multiplication table :
be considered to be abbreviation of 'else if'. num = int(input("Enter the number : "))

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

>=80 and above A


6×1=6
>=70 and <80 B
6 × 2 = 12
>=60 and <70 C
6 × 3 = 18
>=50 and <60 D 6 × 4 = 24
ur

Otherwise E 6 × 5 = 30
m1=int (input("Enter mark in first subject : ")) 6 × 6 = 36
m2=int (input("Enter mark in second subject : ")) 6 × 7 = 42
avg= (m1+m2)/2
.s

6 × 8 = 48
if avg>=80: 6 × 9 = 54
print ("Grade : A") 6 × 10 = 60
elif avg>=70 and avg<80:
w

print ("Grade : B") Hands on Experience


elif avg>=60 and avg<70:
1. Write a program to check whether the given
print ("Grade : C")
w

character is a vowel or not. [QY-2019]


elif avg>=50 and avg<60:
Ans. Program :
print ("Grade : D")
else: ch = input ("Enter a character")
w

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

63
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Using if..else..elif statement check smallest of print("Fibonacci sequence :")
Unit II - Chapter 6

three numbers. print(n1)


Ans. Program : else :
num1 = int(input("Enter first number :")) print("Fibonacci sequence :")
num2 = int(input("Enter second number : ")) print(n1, ",", n2, end = ".")

m
num3 = int(input("Enter third number : ")) while count < nterms :
if(num1 < num2) and (num1 < num3): nth = n1 + n2
smallest=num1

co
print(nth, end = ',')
elif(num2 < num1) and (num2 < num3): n1 = n2
smallest=num2 n2 = nth
else : count + = 1

s.
smallest=num3 Output :
print("The smallest number is", smallest) How many terms? 10
Output : Fibonacci sequence :

ok
Enter first number : 12 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Enter second number : 7 5. Write a program to display sum of natural
Enter third number : 15 numbers, upto n. [QY-2019]
The smallest number is 7 Ans. Program :
o
n = input("Enter any number")
3. Write a program to check if a number is
sum = 0
ab

Positive, Negative or zero.


for i in range(i, n=+1):
Ans. Program : sum = sum + i
num = int(input("Enter a number :")) print "sum =", sum
if num > 0: Output :
ur

print("positive number") Enter any number 5


elif num==0: sum = 15
print("zero") 6. Write a program to check if the given number
.s

else : is a palindrome or not.


Ans. Program :
print("Negative number")
n = int (input("Enter the number:"))
w

4. Write a program to display Fibonacci series 0 1 temp = n


1 2 3 4 5 ......... (upto a terms). rev = 0
Ans. Program : while (n > 0):
w

nterms = int(input("How many terms?")) dig = n%10


rev = rev * 10 + dig
n1 = 0 n = n//10
n2 = 1 if(temp ==rev):
w

count = 2 print ("palindrome"


else:
# check if the number of terms is valid
print ("not a palindrome")
if nterms <=0: Output :
print("please enter a positive integer") Enter any Number 2332
elif nterms ==1: palindrome

64
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


7. Write a program to print the following pattern 4. Match the following : [PTA-4]
***** (a) if...elif - (i) Jump

Control Structures
**** (b) while - (ii) Block
***
(c) pass - (iii) Loop
**
(d) indentation - (iv) Branching
*

m
(a) (a)-(iv), (b)-(iii), (c)-(i), (d)-(ii)
Ans. Program :
(b) (a)-(i), (b)-(iii), (c)-(iv), (d)-(ii)
for i in range (0, 5):
(c) (a)-(iv), (b)-(i), (c)-(iii), (d)-(ii)
for j in range (5, i –1):

co
print ("*", end = '' ") (d) (a)-(i), (b)-(iv), (c)-(ii), (d)-(iii)
print ()  [Ans. (a) (a)-(iv), (b)-(iii), (c)-(i), (d)-(ii)]

8. Write a program to check if the year is leap 5. The optional parameter of range() function in
year or not. Python. [PTA-5]

s.
Ans. Program : (a) start (b) stop
n = int (input ("Enter any year")) (c) step (d) slice
If y % 4 = = 0):  [Ans. (d) slice]

ok
print "Leap Year" 6. Which of the following is not a jump keyword.
else:  [PTA-6]
print "Not a leap Year") (a) pass (b) continue
Output : (c) skip (d) break
o
Enter any Year 2000  [Ans. (c) skip]
Leap Year
2 MARKS
ab

PTA Questions and Answers


1. What will be the output of the following
1 MARK snippet? [PTA-5]
1. What will be the output of the following alpha=list(range(65, 70)
python code? for x in alpha:
ur

[PTA-1]
for i in range(1, 10, 2): print(chr(x), end='\t')
print(i, end=' ') Ans. Output :
(a) 1 3 5 7 9 (b) 1 2 4 6 8 65 66 67 68 69 70
.s

(c) 2 4 6 8 10 (d) 1 3 5 7 10 End of the loop


 [Ans. (a) 1 3 5 7 9]
2. Which is not a jump statement? [PTA-2] 3 MARKS
w

(a) for (b) goto 1. What is the role of range() in for loop of
(c) continue (d) break Python? [PTA-1]
 [Ans. (b) goto] Ans. range (1,30,1) -  will start the range of values
w

3. What will be the output of the following from 1 and end at 29


Python snippet? [PTA-3] range (2,30,2) - will start the range of values
from 2 and end at 28
a=15
w

while (a<=20): range (30,3,-3) - will start the range of values


from 30 and end at 6
print(a%a, end=' ')
range (20) - will consider this value 20 as the
i=i+1
end value(or upper limit) and
(a) 15 16 17 18 19 20 (b) 20 19 18 17 16 15
starts the range count from 0 to
(c) 0 0 0 0 0 0 (d) 1 1 1 1 1 1 19 (remember always range()
 [Ans. (a) 15 16 17 18 19 20] will work till stop -1 value only)
65
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Write the syntax of if....elif....else statement in
for each item
Unit II - Chapter 6

Python. [PTA-3]
in sequence
Ans. Syntax :
if <condition-1>:
statements-block 1
Last item elif <condition-2>:

m
reached? statements-block 2
else:
statements-block n

co
No
5 MARKS
1. Explain briefly about Jump statements in
Body of for Python. [PTA-1, 6]
Ans. The jump statement in Python, is used to
Exit loop unconditionally transfer the control from one

s.
for loop execution part of the program to another. There are three
keywords to achieve jump statements in Python :
2. Draw a flow chart to explain while loop. break, continue, pass. The following flowchart

ok
 [PTA-2] illustrates the use of break and continue.
Ans. while loop
(i) The syntax of while loop in Python has the False
following syntax: Condition

Syntax:
o
True else
while <condition>: Statement 1
Statement 2
Statement 1
statements block 1
ab

... ...
break Statementn
[else: ...
statements block2] continue
...
Further
Statements
Statementn of Program

while Expression:
ur

Use of break, continue statement in loop structure


Statement (s)
(i) break statement : The break statement
Condition
terminates the loop containing it. Control
of the program flows to the statement
.s

if conditions is true immediately after the body of the loop.


if condition is A while or for loop will iterate till the
Conditional Code condition is tested false, but one can
false
even transfer the control out of the loop
w

(terminate) with help of break statement.


When the break statement is executed, the
control flow of the program comes out of
while loop execution
the loop and starts executing the segment
w

(ii) In the while loop, the condition is any of code after the loop structure.
valid Boolean expression returning True If break statement is inside a nested loop
or False. The else part of while is optional (loop inside another loop), break will
w

part of while. The statements block1 is terminate the innermost loop.


kept executed till the condition is True. If Syntax:
break
the else part is written, it is executed when
(ii) continue statement : Continue statement
the condition is tested False. Recall while unlike the break statement is used to skip
loop belongs to entry check loop type, that the remaining part of a loop and start with
is it is not executed even once if the condi- next iteration.
tion is tested False in the beginning. Syntax: continue

66
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iii) pass statement : pass statement is generally Output :
used as a placeholder. When we have a loop 10 11 12 13 14 15

Control Structures
or function that is to be implemented in (ii) for loop :
the future and not now, we cannot develop for loop is the most comfortable loop. It is
such functions or loops with empty body also an entry check loop. The condition is
segment because the interpreter would checked in the beginning and the body of

m
raise an error. So, to avoid this we can use the loop(statements-block 1) is executed
pass statement to construct a body that if it is only True otherwise the loop is not
does nothing.
executed.
Syntax:

co
Syntax :
pass for counter_variable in sequence:
2. What are the different types of loops in statements-block 1
Python? Explain with an example. [PTA-3; 4] [else: # optional block
Ans. (i) while loop statements-block 2]

s.
(a) The syntax of while loop in Python has the  The counter_variable mentioned in the
following syntax: syntax is similar to the control variable
Syntax: that we used in the for loop of C++ and

ok
while <condition>: the sequence refers to the initial, final
statements block 1 and increment value. Usually in Python,
[else: for loop uses the range() function in the
statements block2] sequence to specify the initial, final and
increment values. range() generates a list
o
while Expression: of values starting from start till stop-1.
Statement (s) Example : Examples for range()
ab

Condition range (1,30,1) - will start the range of values


from 1 and end at 29
if conditions is true range (2,30,2) - will start the range of values
Conditional Code
if condition is from 2 and end at 28
false
range (30,3,-3) - will start the range of values
ur

from 30 and end at 6


range (20) - will consider this value 20 as
while loop execution
the end value(or upper limit)
(b) I n the while loop, the condition is any
.s

and starts the range count


valid Boolean expression returning True from 0 to 19 (remember always
or False. The else part of while is optional range() will work till stop -1
part of while. The statements block1 is value only)
w

kept executed till the condition is True. If


(iii) Nested loop structure :
the else part is written, it is executed when
A loop placed within another loop is called
the condition is tested False. Recall while
loop belongs to entry check loop type, that as nested loop structure. One can place
w

is it is not executed even once if the condi- a while within another while; for within
tion is tested False in the beginning. another for; for within while and while
Example : program to illustrate the use of while within for to construct such nested loops.
w

loop - to print all numbers from 10 to 15 Following is an example to illustrate the use of
i=10 # intializing part of for loop to print the following pattern
 the control variable 1
while (i<=15): # test condition 1 2
print (i,end='\t') # statements - block 1 1 2 3
i=i+1 # Updation of the 1 2 3 4
 control variable 1 2 3 4 5

67
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Government Exam Questions and Answers 3 MARKS
Unit II - Chapter 6

1. Which jump statement is used as placeholder?


1 MARK Why? [Govt. MQP-2019]
1. The output of the Segment. [Govt. MQP-2019] Ans. Nested loop structure :
for in range (10, 0, 2) (i) A loop placed within another loop is called

m
as nested loop structure. One can place
print(i)
a while within another while; for within
is another for; for within while and while
(a) 10 9 6 4 2 0 (b) 10 8 6 4 2

co
within for to construct such nested loops.
(c) 0 2 4 6 8 10 (d) Error (ii) Following is an example to illustrate the
[Ans. (d) Error] use of for loop to print the following pat-
tern
2. Which is optional part in range () function? 1

s.
 [QY-2019] 1 2
(a) end (b) step 1 2 3
(c) stop (d) start 1 2 3 4

ok
1 2 3 4 5
[Ans. (b) step]
additional questions and Answers
3. Which statement is used to skip the remaining
part of a loop and start with next iteration? Choose the Correct Answer 1 MARK
 [HY-2019]
o
1. Which of the following are the executable
(a) break (b) continue
segments that yield the result?
(c) return (d) goto
ab

(a) Operator (b) Statements


[Ans. (b) continue] (c) Keywords (d) Identifiers
2 MARKS  [Ans. (b) Statements]

1. What are the types of looping supported by 2. Which of the following is used to alter the
ur

Python? [Govt. MQP-2019] control flow of the process depending on the


state of the process?
Ans. Python provides two types of looping supports:
(a) control structure
(i) while loop
(b) control statement
.s

(ii) for loop (c) program statement


2. Write a Python program to print. [HY-2019] (d) control structure or control statement
1  [Ans. (d) control structure or control
w

statement]
1 2
3. How many important control structures in
1 2 3
python?
w

1 2 3 4 (a) 2 (b) 3
1 2 3 4 5 (c) 4 (d) many
Ans. i = 1  [Ans. (b) 3]
w

while(i<=6):
4. Which of the following is not control
for j in range (1, i): structures?
print (j, end='/t) (a) Sequential (b) Branching
print (end='/n') (c) Operator (d) Looping
i+ = 1  [Ans. (c) Operator]

68
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5. The following statements is an example of 13. Which of the following can be used when the
Print ("ONE") user wants to execute a block of code several

Control Structures
Print ("Four") times bill the condition is satisfied?
(a) iterative (b) branching (a) while (b) if-else
(c) sequential (d) looping (c) if-elif-if (d) all of there
 [Ans. (c) sequential]  [Ans. (a) while]

m
6. What can be learned through alternative or 14. Which of the following function generates the
branching statement? list of values starting from start till stop-1 ?

co
(a) looping (a) sequence() (b) range()
(b) decision making (c) input() (d) print()
(c) functions  [Ans. (b) range()]
(d) classes [Ans. (b) decision making]
15. range (20), the range count from

s.
7. Checking whether the given number is even or (a) 1 to 20 (b) 0 to 19
odd can be done using (c) 1 to 19 (d) 0 to 20
(a) sequential  [Ans. (b) 0 to 19]

ok
(b) alternative or branching
16. Which of the following statement is correct
(c) iterative or looping
when the range will start the values from 1 and
(d) iterative or sequential end at 29?
 [Ans. (b) alternative or branching] (a) range (1, 30, 1) (b) range (1, 29, 1)
o
8. How many types of alternative or branching (c) range (1, 1, 30) (d) range (0, 29, 1)
statements does python provides?  [Ans. (a) range (1, 30, 1)]
ab

(a) 3 (b) 4 17. Write the output for the following program
(c) 2 (d) increase than 3 for I in range (1, 10, 2):
 [Ans. (a) 3] Print (I, end = ' ')
9. Which of the following is not a type of (a) 1, 3, 5, 7, 9 (b) 1, 3, 5, 7
ur

branching statements? (c) 1, 3, 5


(a) if (b) if-else (d) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
(c) if-elif (d) while  [Ans. (b) 1, 3, 5, 7,]
[Ans. (d) while] 18. What will be value of s from the following for
.s

10. Which of the following is not a decision c in range (1, 5)


making statement? s = s + c;
(a) if (b) if-else (a) 15 (b) 5 (c) 1 (d) 10
w

(c) do-while (d) if-elif  [Ans. (c) 1]


 [Ans. (c) do-while] 19. Which of the following is not a nested loop?
w

11. Which of the following statement provided (a) for within while (b) for within if
control to check the true and false block? (c) while within for
(a) if (b) while (d) while within while [Ans. (b) for within it]
(c) do-while (d) if-else
w

 [Ans. (d) if-else] 20. Which statement in python used to transfer


the center from one part of the program to
12. To construct a chain of if statement, else can
be replaced by another unconditionally?
(a) Jump (b) loop
(a) while (b) ifel
(c) alternative (d) iterative
(c) else if (d) elif[Ans. (d) elif]
 [Ans. (a) Jump]

69
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


21. How many keywords are there to achieve jump 2. The program statements executed for multiple
Unit II - Chapter 6

statements in python? times are called ___________


(a) 2 (b) 4 (c) 3 (d) 5 (a) alterative (b) looping
 [Ans. (c) 3]
(c) branching (d) objects
22. Which statement transfers the control out of  [Ans. (b) looping]

m
loop even when the loop condition is tested
true? 3. The program statements which are executed
(a) continue (b) break one after another is called ___________
(c) pass (d) goto statements.

co
 [Ans. (b) break] (a) sequential (b) iterative
(c) Branching (d) looping
23. Which part of the loop is not executed if a loop
 [Ans. (a) sequential]
is left by break?
(a) if (b) else 4. In if-else statement which block is to be

s.
(c) break (d) for executed is determined by a __________
 [Ans. (b) else] (a) Operator (b) operands
(c) condition (d) identifier

ok
24. Which statement is used to skip the remaining
part of a loop and start with next iteration?  [Ans. (c) condition]
(a) continue (b) break 5. Python provides _______types of looping
(c) pass (d) condition constructs.
 [Ans. (a) continue]
o
(a)
3 (b) 2 (c) 4 (d) 6
25. Which of the following statement is used as a  [Ans. (b) 2]
place holder in python?
ab

6. In the ____________loop, the condition is any


(a) continue (b) break valid boolean expression returning True or
(c) pass (d) if [Ans. (c) pass] false.
Choose odd man out (a) if (b) else
(c) eif (d) while
ur

1. (a) Branching (b) looping


(c) sequential (d) Condition  [Ans. (d) while]
 [Ans. (d) Condition] 7. The ____________part of while is optional
part of while.
.s

2. (a) keywords (b) Operator


(c) Identifiers (d) Programs (a) if (b) else
 [Ans. (d) Programs] (c) elif (d) condition
[Ans. (b) else]
w

3. (a) Statement (b) Operator


(c) Identifier (d) Keyword 8. In Python for loop, the __________refers to
 [Ans. (a) Statements] the initial, final and increment value.
w

4. (a) continue (b) for (a) else (b) sequence


(c) break (d) pass (c) range (d) b or c
 [Ans. (d) b or c]
 [Ans. (b) for]
w

9. In Python, for loop uses the _________


Choose and fill in the blanks function in the sequence to specify the initial,
1. The program segment executed based on the final and increment values.
test of the condition are called _____________
(a) Input () (b) print ()
(a) statement (b) iteration
(c) range () (d) sequence ()
(c) branding (d) looping
 [Ans. (c) range ()]
 [Ans. (c) branding]
70
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. In range (30, 3, -3), -3 denotes _______ value. (iii)
python provides three types of loop
(a) start (b) stop constructs.

Control Structures
(c) step (d) final (iv) if – elif – else is not similar to C++ nested if.
 [Ans. (c) step] (a) i and ii (b) ii and iii
(c) iii and iv (d) i and iv
11. range (30, 3, -3)-will start the range of values

m
from _____and end at_______.  [Ans. (c) iii and iv]
(a) 30, 3 (b) 30, -3 2. (i) In for loop, the condition is checked in the
(c) 30, 6 (d) 30, 0 beginning.

co
 [Ans. (c) 30, 6] (ii) In for loop range () function in the
12. A loop placed within another loop is called as resurgence to specify the initial, final and
________loop structure. increment values.
(a) entry check (b) exit check (iii) range () generates a list of values starting

s.
(c) nested (d) conditional from start till stop – 1
 [Ans. (c) nested] (iv) The syntax of range is range (start, step,
stop)

ok
13. Control of the program flows to the statements
immediately after the body of the loop by using (a) (i) only
_____statements. (b) (ii) and (iv)
(a) continue (b) pass (c) (iv) only
(c) break (d) goto (d) (i), (ii), (iii) and (iv)
o
 [Ans. (c) break]  [Ans. (c) (iv) only]
14. If break statement is inside a nested loop,
ab

3. (i) J ump statements transfer the control from are


______________ will terminate the innermost
part of the program to another conditionally.
loop.
(a) continue (b) Pass (ii) goto, continue, pass are the three jump
statements in python.
(c) goto (d) break
ur

 [Ans. (d) break] (iii) In Python, indentation is important in loop


Choose the correct statement and other control statements.
(iv) Pass statement used as a place holder.
1. (i) alternative statement also called branching
(a) i and ii (b) ii and iii
.s

(ii) iteration also called branching


(c) iii and iv (d) i and iv
(iii) alternative statements also called looping
(iv) branching also called looping  [Ans. (a) i and ii]
w

(a) (i) is correct 4. (i) if a loop is left by break, the else part is not
(b) (ii) and (iv) are correct executed
(c) (iii) is correct (ii) Continue statement is used to skip the
w

(d) (i), (ii), (iii) and (iv) are correct remaining part of a loop and start with next
 [Ans. (a) (i) is correct] iteration.
Choose the incorrect statement (iii) In python, pass statement is a null statement.
w

1. Which of the following statements are (iv) In python, pass statement is not completely
incorrect? ignored by the complier.
(i) In a if statement there is no limit of elif (a) i and ii (b) iii only
clause that can be use(d) (c) iii and iv (d) iv only
(ii) 'else' clause if used should be placed at the  [Ans. (d) iv only]
en(d)

71
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose the true or false statement Output 1:
Unit II - Chapter 6

Enter any number :3


1. State whether the following statement is true/
false. 3 is odd
(i) While loop is an entry check loop Output 2:
(ii) for loop is an entry check loop Enter any number :22

m
(iii) print() can have parameters 22 is even
(iv) if-elif-else is similar to c++ nested if. 5. Write a note on the parameters used in
(a) i – true, ii – true, iii-true, iv-true print () statement.

co
(b) i-true, ii-false, iii-true, iv-true Ans. (i) print can have end, sep as parameters. end
(c) i-true, ii-true, iii-false, iv-true parameter can be used when we need to
(d) i-true, ii-true, iii-true, iv-true give any escape sequences like '\t' for tab,
 [Ans. (a) i – true, ii – true, iii-true, iv-true] '\n' for new line and so on.
(ii) sep as parameter can be used to specify

s.
Very Short Answers 2 MARKS
any special characters like, (comma) ;
1. What is meant by alternative or branching? (semicolon) as separator between values
Ans. There may be situations in our real life

ok
6. Write the syntax of for loop.
programming where we need to skip a segment
Ans. Syntax:
or set of statements and execute another segment
based on the test of a condition. This is called for counter_variable in sequence:
alternative or branching. statements-block 1
[else: # optional block
o
2. Write a program in python to check if the
statements-block 2]
accepted number even or odd.
ab

a = int(input("Enter any number :")) 7. Draw the flowchart that illustrate the working
if a%2==0: of for loop.
print (a, " is an even number") Ans.
else: for each item
print (a, " is an odd number") in sequence
ur

Ans. Output 1:
Enter any number :56 Yes
Last item
56 is an even number reached?
.s

Output 2:
Enter any number :67
67 is an odd number No
w

3. Write the syntax of alternative method to write Body of for


complete if-else. Exit loop
Ans. Syntax:
w

for loop execution


variable = variable1 if condition else variable 2
8. What will the output of the following program?
4. Write a program in python to check if the for i in range (1, 9, 2):
accepted number us even or odd (use alternate
w

print (i, end = ' ')


method of if-else).
else:
Ans. a = int (input("Enter any number :"))
print (")n End of the loop")
x="even" if a%2==0 else "odd"
Ans. Output:
print (a, " is ",x)
1, 3, 5, 7
End of the loop

72
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


9. What is the expression or statement at ?1? and 16. Write the syntax how break statement used in
?2? in the following program to get the output for loop.

Control Structures
2468 Ans. for var in sequence:
for ?1? in range (2, ?2?, 2): if condition:
print (i, end = ") break
Ans. ?1? – i #code inside for loop

m
?2? – 10 #code outside for loop
10. Write a python program to calculate the sum 17. Write the syntax how break statement used in
of numbers between 1 and 100. while loop.

co
Ans. Program to calculate the sum of numbers 1 to Ans. while test expression:
100 #code inside while loop
Program : if condition:
n = 100 break
sum = 0
#code inside while loop

s.
for counter in range(1,n+1):
#code outside while loop
sum = sum + counter
print("Sum of 1 until %d: %d" % (n,sum)) 18. What is the use of continue statement in
python?

ok
Output:
Sum of 1 until 100: 5050 Ans. Continue statement unlike the break statement
is used to skip the remaining part of a loop and
11. Write a python program to find the sum of start with next iteration.
even numbers between 1 and 10.
19. What will the output the following
Ans. s = 0
o
for w in "school"?
For i in range (2, 11, 2)
s=s+i If w = = '0':
continue
ab

print (s)
print (w)
12. Write a python program to find the sum of odd
Ans. schl
numbers between 10 and 20.
Ans. s = 0 20. Write a note an pass statement.
for i in range (11, 21, 2) Ans. pass statement in Python programming is a null
ur

s=s+i statement. pass statement when executed by the


print (s) interpreter it is completely ignored. Nothing
happens when pass is executed, it results in no
13. What are the values taken by range ()? operation.
.s

Ans. It take values from string, list, dictionary.


Short Answers 3 MARKS
14. What is meant by Nested loop structure?
1. Write a note on sequential statement with an
Ans. A loop placed within another loop is called as
example.
w

nested loop structure. A while within another


while; for within another for; for within while Ans. A sequential statement is composed of a
and while within for to construc nested loops. sequence of statements which are executed one
after another. A code to print your name, address
15. What is the use of Jump statements in python?
w

and phone number is an example of sequential


(or) statement.
What are the statements are there to achieve Example :
jump statements in python? # Program to print your name and address -
w

Ans. The jump statement in Python, is used to example for sequential statement
unconditionally transfer the control from one print ("Hello! This is Shyam")
part of the program to another. There are three print ("43, Second Lane, North Car Street, TN")
keywords to achieve jump statements in Python:
Output :
break, continue, pass. The following flowchart
illustrates the use of break and continue. Hello! This is Shyam
43, Second Lane, North Car Street, TN

73
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. List the types of alternative or branching 6. Write the syntax of working of continue
Unit II - Chapter 6

statement in python. statement in for and while loop.


Ans. Python provides the following types of alternative Ans. for var in sequence:
or branching statements: # code inside for loop
(i) Simple if statement if condition:
(ii) if..else statement continue

m
(iii) if..elif statement #code inside for loop
3. Write a python program to print all numbers #code outside for loop
from 10 to 15 using while loop. while test expression:

co
Ans. Example : Program to illustrate the use of while #code inside while loop
loop - to print all numbers from 10 to 15 if condition:
i=10  # intializing part of the control continue
variable #code inside while loop
while (i<=15): # test condition #code outside while loop

s.
print (i,end='\t') # statements - block 1 7. What is the output of the following Python
i=i+1 # Updation of the control variable program?
Output: Ans. i=10 #
 intializing part of the control variable

ok
10 11 12 13 14 15 while (i<=15): # test condition
4. Draw a flowchart that illustrates the working print (i,end='\t') # statements - block 1
of while loop. i=i+1 # Updation of the control variable
Ans. else:
print ("\nValue of i when the loop exit ",i)
o
Output: 1
while Expression: 10 11 12 13 14 15
Value of i when the loop exit 16
ab

Statement (s)
Condition
8. Draw a flowchart that illustrate how looping
if conditions is true
construct gets executed.
if condition is Ans.
Conditional Code
ur

false
False
Condition

while loop execution


True else
.s

Statement 1
5. Write a program in python that illustrate the Statement 1 Statement 2
use of 'in' and 'not in' if statement Statement 2 ...
... Statementn
Ans. Program :
w

Statementn
ch=input ("Enter a character :") Further
# to check if the letter is vowel Statements
if ch in ('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'): of Program
w

print (ch,' is a vowel') Diagram to illustrate how looping construct gets executed
# to check if the letter typed is not 'a' or 'b' or 'c'
if ch not in ('a', 'b', 'c'): 9. What will be output of the following program?
w

print (ch,' the letter is not a/b/c') Ans. for word in "Jump Statement":
Output 1: if word = = "e":
Enter a character :e break
e is a vowel print (word, end=")
Output 2: else:
Enter a character :x print ("End of the loop")
x the letter is not a/b/c print ("\n End of the program")
74
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Output: 2. Write a program in python to display the
Jump Stat following output.

Control Structures
End of the program (i) 5 5 5 5 5
10. Why we need to construct the pass statement? 4444
Ans. pass statement is generally used as a placeholder. 333
When we have a loop or function that is to be

m
22
implemented in the future and not now, we
1
cannot develop such functions or loops with
empty body segment because the interpreter (ii) 1 2 3 4 5

co
would raise an error. So, to avoid this we can 1234
use pass statement to construct a body that does 123
nothing. 12
Long Answers 5 MARKS 1
1. Write a program in python to display he Ans. (i) for i in range (5, 0,-1):

s.
following output for j in range (1, i + 1):
1 print (i, end = ' ')
22

ok
print (end = '\n')
333
4444 i+=1
55555 (ii) for i in range (5, 0, -1):
Ans. for i in range (1,6): for j in range (1, i + 1):
for j in range (1, i + 1) print (j end = ' ')
o
print (i, end = ' ') print (i, end = '\n')
print (end = '\n')
ab

i+=1 i+=1


ur
.s
w
w
w

75
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

PYTHON  
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

 

7
Chapter
FUNCTIONS

m
co
CHAPTER SNAPSHOT

s.
7.01 Introduction
7.1.1 Types of Functions
7.02 Defining Functions

ok
7.2.1 Syntax for User defined function
7.2.2 Advantages of User-defined Functions
7.03 Calling a Function
7.04 Passing Parameters in Functions
o
7.05 Function Arguments
7.5.1 Required Arguments
ab

7.5.2 Keyword Arguments


7.5.3 Default Arguments
7.5.4 Variable-Length Arguments
7.06 Anonymous Functions
ur

7.6.1 Syntax of Anonymous Functions


7.07 The return Statement
7.7.1 Syntax of return
7.08 Scope of Variables
.s

7.8.1 Local Scope


7.8.2 Global Scope
7.8.3 Global and local variables
w

7.09 Functions using libraries


7.9.1 Built-in and Mathematical functions
7.9.2 Composition in functions
w

7.10 Python recursive functions


w

[76]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science

Evaluation 9. Pick the correct one to execute the given


statement successfully.

Python Functions
if ____ : print(x, " is a leap year")
Part - I (a) x%2=0 (b) x%4==0
(c) x/4=0 (d) x%4=0
Choose the best answer  (1 mark)  [Ans. (b) x%4==0]

m
1. A named blocks of code that are designed to 10. Which of the following keyword is used to
do one specific job is called as define the function testpython(): ?
(a) Loop (b) Branching (a) define (b) pass
(c) Function (d) Block (c) def (d) while

co
 [Ans. (c) Function ]  [Ans. (c) def]
2. A Function which calls itself is called as
(a) Built-in (b) Recursion Part - II
(c) Lambda (d) return Answer the following questions
 [Ans. (b) Recursion]  (2 marks)

s.
3. Which function is called anonymous un-named 1. What is function?
function Ans. (i) Functions are named blocks of code that
(a) Lambda (b) Recursion are designed to do one specific job.

ok
(c) Function (d) define
(ii) Types of Functions are User defined, Built-
 [Ans. (a) Lambda]
4. Which of the following keyword is used to in, lambda and recursion.
begin the function block? (iii) Function blocks begin with the keyword
(a) define (b) for "def " followed by function name and
o
(c) finally (d) def parenthesis ().
 [Ans. (d) def] 2. Write the different types of function. [PTA-3]
ab

5. Which of the following keyword is used to exit Ans. (i) User - defined functions.
a function block?
(ii) Built in functions.
(a) define (b) return
(c) finally (d) def (iii) Lambda functions.
 [Ans. (b) return] (iv) Recursion functions.
ur

6. While defining a function which of the 3. What are the main advantages of function?
following symbol is used.  [HY-2019]
(a) ; (semicolon) (b) . (dot) Ans. Main advantages of functions are
(c) : (colon) (d) $ (dollar)
(i)  It avoids repetition and makes high degree
.s

 [Ans. (c) : (colon)]


of code reusing.
7. In which arguments the correct positional
order is passed to a function? (ii)  It provides better modularity for your
(a) Required (b) Keyword application.
w

(c) Default (d) Variable-length 4. What is meant by scope of variable? Mention


 [Ans. (a) Required] its types.
8. Read the following statement and choose the Ans. Scope of variable refers to the part of the
w

correct statement(s). program, where it is accessible, i.e., area where


(I) In Python, you don’t have to mention the the variables can refer (use). The scope holds
specific data types while defining function. the current set of variables and their values. The
(II) Python keywords can be used as function
w

two types of scopes are - local scope and global


name. scope.
(a) I is correct and II is wrong 5. Define global scope.
(b) Both are correct
Ans. A variable, with global scope can be used
(c) I is wrong and II is correct
anywhere in the program. It can be created by
(d) Both are wrong
defining a variable outside the scope of any
 [Ans. (a) I is correct and II is wrong]
function/block.

77
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


6. What is base condition in recursive function? 3. What happens when we modify global variable
 [PTA-6] inside the function?
Unit II - Chapter 7

Ans. (i) A recursive function calls itself. Ans. If we modify the global variable, we can see
(ii) The condition that is applied in any recursive the change on the global variable outside the
function is known as base condition. function also.
(iii) A base condition is must in every recursive Example:

m
function otherwise it will continue to x = 0 # global variable
execute like an infinite loop. def add():
7. How to set the limit for recursive function? global x

co
Give an example. [PTA-5] x = x + 5 # increment by 2
Ans. (i) Python stops calling recursive function print ("Inside add() function x value is :", x)
after 1000 calls by default. add()
(ii) So, it also allows you to change the limit print ("In main x value is :", x)
using sys.setrecursionlimit (limit_value). Output :

s.
Example: Inside add() function x value is : 5
import sys In main x value is : 5 # value of x changed
sys.setrecursionlimit(3000)  outside the function
def fact(n):

ok
if n == 0: 4. Differentiate ceil() and floor() function.
return 1 Ans.  [PTA-2]
else:
return n * fact(n-1) S.No. ceil () floor ()
print(fact (2000))
o
(i) Returns the smallest Returns the largest
integer greater that integer less than or
Part - III or equal to x. equal to x.
ab

Answer the following questions (ii) Syntax : math.ceil(x) Syntax : math.floor(x)


 (3 marks)
5. Write a Python code to check whether a given
1. Write the rules of local variable. year is leap year or not.
Ans. Rules of local variable :
Ans. Code :
ur

(i)  A variable with local scope can be accessed


n=int(input("Enter the year"))
only within the function/block that it is
created in. if(y%4==0):
(ii) When a variable is created inside the print ("Leap Year")
.s

function/block, the variable becomes local else:


to it. print ("Not a Leap Year")
(iii) 
A local variable only exists while the Output :
w

function is executing. Enter the year 2012


(iv) The formate arguments are also local to Leap Year
function.
6. What is composition in functions?
2. Write the basic rules for global keyword in
w

python. [PTA-4] Ans. (i) The value returned by a function may be


Ans. Rules of global Keyword : The basic rules for used as an argument for another function
global keyword in Python are: in a nested manner.
w

(i)  When we define a variable outside a (ii) This is called composition. For example,
function, it’s global by default. You don’t if we wish to take a numeric value or an
have to use global keyword. expression as a input from the user, we take
(ii) We use global keyword to read and write a the input string from the user using the
global variable inside a function. function input() and apply eval() function
(iii) 
Use of global keyword outside a function to evaluate its value
has no effect.

78
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


7. How recursive function works? (ii) Built-in Functions : Functions which are
Ans. (i)  Recursive function is called by some using Python libraries are called Built-in

Python Functions
external code. function.
(ii) If the base condition is met then the x=20
program gives meaningful output and exits. y=-23.2
(iii) Otherwise, function does some required print('x = ', abs(x))

m
processing and then calls itself to continue print('y = ', abs(y))
recursion. Output:
8. What are the points to be noted while defining x = 20

co
a function? [Govt. MQP-2019] y = 23.2
Ans. When defining functions there are multiple
(iii) Lambda Functions :
things that need to be noted; ■  In Python, anonymous function is a
function that is defined without a name.
(i)  Function blocks begin with the keyword ■  While normal functions are defined using

s.
"def" followed by function name and
the def keyword, in Python anonymous
parenthesis ().
functions are defined using the lambda
(ii)  Any input parameters or arguments should keyword.
be placed within these parentheses when

ok
■  Hence, anonymous functions are also
you define a function.
called as lambda functions.
(iii)  The code block always comes after colon(;)
Example :
and is indented.
sum = lambda arg1, arg2: arg1 + arg2
(iv)  The statement "return [expression]"
print ('The Sum is "', sum(30,40))
o
exits a function, optionally passing back an
expression to the caller. A "return" with no pint ('The Sum is :', sum(–30,40))
arguments is the same as return None. Output :
ab

Part - IV The Sum is : 70


The Sum is : 10
Answer the following questions (iv) Recursive function : Functions that calls
 (5 marks) itself is known as recursive.
ur

1. Explain the different types of function with an Overview of how recursive function
example. [Govt. MQP-2019; PTA-4] works :
Ans. Functions are named blocks of code that are (i)  Recursive function is called by some
designed to do one specific job. external code.
.s

Types of Functions : (ii) If the base condition is met then the
(i) User Defined Function program gives meaningful output and exits.
(ii) Built-in Function (iii) 
Otherwise, function does some required
w

(iii) Lambda Function processing and then calls itself to continue


(iv) Recursion Function recursion.
(i) User Defined Function : Example :
■  def fact(n):
w

Functions defined by the users themselves


are called user defined function. if n == 0:
■  Functions must be defined to create and return 1
use certain functionality. else:
w

■  Function blocks begin with the keyword return n * fact (n-1)


"def " followed by function name and print (fact (0))
parenthesis (). print (fact (5))
Example : Output:
def area(w,h):
return w * h 1
print (area (3,5)) 120

79
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Explain the scope of variables with an example. Example : Accessing global Variable From
 [PTA-3; HY-2019] Inside a Function
Unit II - Chapter 7

Ans. Scope of variable refers to the part of the c = 1 # global variable


program, where it is accessible, i.e., area where def add():
the variables refer (use). The scope holds the print(c)
add()

m
current set of variables and their values. The two
Output:
types of scopes - local scope and global scope.
1
Local Scope : A variable declared inside the
3. Explain the following built-in functions.

co
function's body or in the local scope is known as
local variable. (a) id() (b) chr()
(c) round() (d) type()
Rules of local variable :
(e) pow()
(i) 
A variable with local scope can be accessed
Ans.

s.
only within the function/block that it is
created in. (a)  [PTA-4, 6; QY-2019]

(ii) 
When a variable is created inside the Function Description Syntax Example

ok
function/block, the variable becomes local id () id( ) Return id x=15
to it. the “identity” (object) y='a'
(iiii) A local variable only exists while the of an object. print ('address
function is executing. i.e. the of x is :',id (x))
o
(iv) 
The formal arguments are also local to address of
the object in print ('address
function.
memory. of y is :',id (y))
ab

(v) Example: Create a Local Variable


Note: Output:
def loc():
The address address of x
y=0 # local scope
of x and y is :
print(y)
ur

may differ in 1357486752


loc() your system. address of y
Output: is :
0 13480736
.s

Global Scope : A variable, with global scope (b)  [PTA-4]


can be used anywhere in the program. It can be
Function Description Syntax Example
created by defining a variable outside the scope
w

of any function/block. chr ( ) Returns the chr (i) c=65


Rules of global Keyword : Unicode d=43
character print (chr (c))
w

The basic rules for global keyword in Python are:


for the given
(i) 
When we define a variable outside a prin t(chr (d))
ASCII value.
function, it’s global by default. You don’t Output:
This function
w

have to use global keyword. A


is inverse
(ii) 
We use global keyword to read and write a +
of ord()
global variable inside a function.
function.
(iii) 
Use of global keyword outside a function
has no effect.

80
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(c) 4. Write a Python code to find the L.C.M. of two
numbers.

Python Functions
Function Description Syntax Example
Ans. Program :
round ( ) Returns round x= 17.9 def lcm(x, y):
the nearest (number y= 22.2 if x>y:
integer to its [,ndigits]) z= -18.3 greater = x

m
input. print ('x
value is else:
1. First greater = y
argument rounded
to', round while (True):
(number)

co
(x)) if ((greater % x == 0) and (greater % y ==
is used to 0)):
print ('y
specify the
value is lcm = greater
value to be rounded break
rounded. to', round greater + = 1

s.
(y)) return lcm
print ('z a = int (input ("Enter first number :"))
value is b = int (input ("Enter second number :"))
rounded

ok
print ("The LCM of ", a, "and", b, "is", LCM(a,b))
to', round
(z)) 5. Explain recursive function with an example.
 [PTA-5]
(d) [PTA-4; QY-2019]
Ans. (i) A Functions that calls itself is known as
Function Description Syntax Example recursive.
o
type ( ) Returns the type x= 15.2 (ii) When a function calls itself is known as
type of object (object) y= 'a' recursion.
ab

for the given s= True (iii) Recursion works like loop but sometimes
single object. print (type it makes more sense to use recursion than
Note: (x)) loop.
This function print (type (iv) Imagine a process would iterate indefinitely
used with (y)) if not stopped by some condition is known
ur

single object print (type as infinite iteration.


parameter. (s)) (v) The condition that is applied in any recursive
Output: function is known as base condition.
<class 'float'> (vi) A base condition is must in every recursive
.s

<class 'str'> function otherwise it will continue to


<class 'bool'> execute like an infinite loop.
(e) (vii) Python stops calling recursive function
w

Function Description Syntax Example after 1000 calls by default.


pow ( ) Returns the pow (a,b) a= 5 (viii) So, It also allows you to change the limit
computation b= 2 using sys.setrecursionlimit (limit_value).
Overview of how recursive function works :
w

of ab i.e. c= 3.0
(a**b) a print (pow (i) Recursive function is called by some
raised to the (a,b)) external code.
power of b. print (pow (ii)  If the base condition is met then the
w

(a,c)) program gives meaningful output and exits.


print (pow (iii) Otherwise, function does some required
(a+b,3)) processing and then calls itself to continue
Output: recursion.
25
Here is an example of recursive function
125.0
343 used to calculate factorial.

81
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Example : 3. Evaluate the following functions and write the
def fact(n): output.
Unit II - Chapter 7

if n == 0: Sl.No. function Output


return 1 1. 1. abs (-25+12.0)
else: 2. abs (-3.2)

m
return n * fact (n-1) 2. 1. ord('2)
print (fact (0)) 2. ord($')
print (fact (5)) 3. type('s')

co
Output: 4. bin(16)
1 5. 1. chr(13)
120
Hands on Practice 2. print(chr(13))
6. 1. round(18.2,1)

s.
1. Try the following code in the above program. 2. round(18.2,0)
Sl.No. Code Result 3. round(0.5100,3)
4. round(0.5120,3)
1. printinfo("3500")

ok
7. 1. format(66, 'c')
2. printinfo("3500","Sri"))
2. format(10, 'x')
3. printinfo(name="balu") 3. format(10, 'X')
4. printinfo("Jose", 1234) 4. format(0b110, 'd')
o
5. printinfo(" ",salary=1234) 5. format(0xa, 'd')
Ans. Output : 8. 1. pow(2,-3)
ab

1. Error 2. pow(2,3.0)
2. Name : Sri 3. pow(2,0)
Salary : 3500 4. pow(1+2),2)
3. Name : Balu 5. pow(-3,2)
6. pow(2*2,2)
ur

Salary : 3500
4. Name : Jose Ans. Output :
1. 1. 13
Salary : 1234
2. 3.2
5. Name :
.s

2. 1. 50
Salary : 1234 2. 36
3. <class 'str'>
2. Evaluate the following functions and write the
4. 0b10000
output.
w

5. 1. CR (carriage return)
Sl.No. Function Output 2. It moves the cursor to the beginning of
same line
1. eval('25*2-5*4')
6. 1. 18.2
w

2. math.sqrt(abs(-81) 2. 18.0
3. math.ceil(3.5+4.6) 3. 0.510
4. 0.512
4. math.floor(3.5+4.6)
w

7. 1. B
Ans. Output : 2. a
1. 30 3. A
4. 6
2. 9
5. 10
3. 8 8. 1. 0.125
4. 9 2. 8.0
3. 1
82
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. What is the use of lambda function? [PTA-2]
PTA Questions and Answers
Ans. (i) Lambda function is mostly used for creating

Python Functions
1 MARK small and one-time anonymous function.
1. Which function is called anonymous function? (ii) Lambda functions are mainly used in
combination with the functions like filter(),
 [PTA-1]
map() and reduce().

m
(a) Lambda (b) Recursion
(c) Function (d) define
 [Ans. (a) Lambda] 5 MARKS
2. Which of the following special character is

co
1. Explain about Lambda function with suitable
used to define variable length arguments? example. [PTA-2]
 [PTA-2]
Ans. In Python, anonymous function is a function
(a) & (b) $ (c) * (d) #
that is defined without a name. While normal
 [Ans. (c) *]
functions are defined using the def keyword,

s.
3. Which keyword to be used to define a function
in Python anonymous functions are defined
in Python? [PTA-3]
using the lambda keyword. Hence, anonymous
(a) def (b) local
functions are also called as lambda functions.

ok
(c) rec (d) global
 [Ans. (a) def] (i)  Lambda function is mostly used for
4. Non-keyword variable arguments are called as creating small and one-time anonymous
(a) Sets (b) List [PTA-4] function.
(c) Tuples (d) Dictionary (ii) Lambda functions are mainly used in
o
 [Ans. (c) Tuples] combination with the functions like filter(),
5. What will be the output of the following map() and reduce ().
ab

Python snippet? [PTA-5] Syntax of Anonymous Functions


c=5
The syntax for anonymous functions is as
def add():
follows:
c=c+5
print(c) Example :
ur

add() lambda [argument(s)] :expression


(a) 5 (b) 10 sum = lambda arg1, arg2: arg1 + arg2
(c) 15 (d) Error print ('The Sum is :', sum(30,40))
 [Ans. (d) Error]
.s

print ('The Sum is :', sum(-30,40))


6. Which of the following is not an argument
type? [PTA-6] Output :
(a) Required arguments The Sum is : 70
w

(b) Default arguments The Sum is : 10


(c) Keyword arguments The above lambda function that adds argument
(d) Fixed length arguments arg1 with argument arg2 and stores the result in
w

 [Ans. (d) Fixed length arguments] the variable sum. The result is displayed using
2 MARKS the print().

1. Write the syntax of creating User Defined Government Exam Questions and Answers
w

Function in Python. [PTA-1]


Ans. Syntax for User defined function : 1 MARK
def <function_name ([parameter1, 1. The bin() function returns a binary string
 parameter2…] )> : prefixed with: [Govt. MQP-2019]
<Block of Statements> (a) 0 (b) 1 (c) 0b (d) 1b
return <expression / None>
[Ans. (c) 0b]
83
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. What is the output of the following program: 2. Define short notes on floor division operator.
 [QY-2019]  [QY-2019]
Unit II - Chapter 7

c=1 Ans. floor ( ) - Returns the largest integer less than or


def add(): equal to x
print(c) Syntax : math.floor (x)
add() x=26.7

m
(a) 1 (b) 0 y=-26.7
(c) none (d) C z=-23.2
[Ans. (a) 1] print (math.floor (x))

co
print (math.floor (y))
3. What is the output of the function Print print (math.floor (z))
(Chr(66))? [QY-2019] Output:
(a) A (b) C 26
(c) b (d) B -27

s.
[Ans. (d) B] -24
4. Evaluate the following function and write the 3. Describe the abs() and chr() function.
output. [HY-2019]  [QY-2019]

ok
x = –37.9 Ans. abs ( ) - Returns absolute value of a number
print(math.cell(x)) chr ( ) - Returns a Character (a string) from an
(a) –38 (b) –39 Integer
(c) –36 (d) –37
o
[Ans. (d) –37] 3 MARKS
2 MARKS 1. Evaluate the following function. [QY-2019]
ab

1. Define Operator and Operand. a) math.ceil (3.5) b) abs (–3.2)


 [Govt. MQP-2019] c) Pow (2, 0)
Ans. Operators are categorized as Arithmetic, Ans. a) math.ceil (3.5) = 4
Relational, Logical, Assignment etc. Value and b) abs (–3.2) = 3.2
ur

variables when used with operator are known as c) Pow (2,0) = 1


operands.
.s

2. What is the use of format () function? Give an example. [QY-2019]


Ans.
Function Description Syntax Example
w

format ( ) Returns the output based on format (value x= 14


the given format [, format_spec]) y= 25
w

1. Binary format. Outputs print ('x value in binary :',format(x,'b'))


the number in base 2. print ('y value in octal :',format(y,'o'))
2. Octal format. Outputs print('y value in Fixed-point no
w

the number in base 8. ',format(y,'f '))


3. Fixed-point notation. Output:
Displays the number as a
x value in binary : 1110
fixed-point number. The
y value in octal : 31
default precision is 6.
y value in Fixed-point no : 25.000000

84
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5 MARKS Output:
Example-1 Keyword arguments

Python Functions
1. Explain various function arguments in Name :Gshan
Python. [QY-2019] Default Arguments :
Ans. Required Arguments : (i) In Python the default argument is an
(i) “Required Arguments” are the arguments argument that takes a default value if no

m
passed to a function in correct positional value is provided in the function call. The
order. Here, the number of arguments in following example uses default arguments,
the function call should match exactly that prints default salary when no argument
with the function definition. Atleast one

co
is passed.
parameter to prevent syntax errors to get
(ii) Example :
the required output.
(ii) Example :
def printinfo( name, salary = 3500):
def printstring(str): print (“Name: “, name)
print ("Example - Required arguments") print (“Salary: “, salary)

s.
print (str) return
return printinfo(“Mani”)
# Now you can call printstring() function (iii) When the above code is executed, it

ok
printstring ("Welcome") produces the following output
Output: Output:
Example - Required arguments Name: Mani
Welcome Salary: 3500
(iii) When the above code is executed, it (iv) When the above code is changed as print
o
produces the following error. info(“Ram”,2000) it produces the following
Traceback (most recent call last): output:
ab

File "Req-arg.py", line 10, in <module>


Output:
printstring()
Name: Ram
TypeError: printstring() missing 1 required
positional argument: 'str' Salary: 2000
(iv) Instead of printstring() in the above code Syntax - Variable-Length Arguments :
(i) def function_name(*args):
ur

if we use printstring (“Welcome”) then the


output is function_body
Output: return_statement
Example - Required arguments (ii) Example :
.s

Welcome def printnos (*nos):


Keyword Arguments : for n in nos:
(i) Keyword arguments will invoke the function print(n)
after the parameters are recognized by their return
w

parameter names. The value of the keyword # now invoking the printnos() function
argument is matched with the parameter print ('Printing two values')
name and so, one can also put arguments in
printnos (1,2)
w

improper order (not in order).


print ('Printing three values')
(ii) Example :
def printdata (name): printnos (10,20,30)
print (“Example-1 Keyword Output :
w

arguments”) Printing two values


print (“Name :”,name) 1
return 2
# Now you can call printdata() function Printing three values
printdata(name = “Gshan”) 10
(iii) When the above code is executed, it 20
produces the following output : 30
85
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. What will be the output if the return has no
Additional questions and answers argument?
Unit II - Chapter 7

Choose the Correct Answer 1 MARK (a) No (b) Return


(c) None (d) End
1. Which of the following is used, if you don’t
need to type all the python code for the same  [Ans. (c) None]

m
task again and again: 11. Which of the following are the values pass to
(a) Statement (b) Function the function parameters?
(c) Scope (a) Variables (b) Arguments
(c) Definitions (d) Identifiers

co
(d) Control structures [Ans. (b) Function]
2. Which of the following avoids repetition and  [Ans. (b) Arguments]
makes high degree of code reusing? 12. How many types of arguments are used to call
(a) Loop (b) Branching a function ?
(c) Functions (d) Dictionaries (a) 3 (b) 4 (c) 5 (d) 2

s.
 [Ans. (c) Functions]  [Ans. (b) 4]
3. Which of the following provides better 13. Which of the following is not a type of
modularity for your python application arguments used to call a function?

ok
(a) function (b) tuples (a) Required (b) Keywords
(c) dictionaries (d) control structures (c) Default (d) Module
 [Ans. (a) function]  [Ans. (d) Module]
4. How many types of functions are there in 14. In which of the following the number of
python? arguments in the function call should match
o
(a) 3 (b) 4 (c) 2 (d) 5 exactly with the function definition?
 [Ans. (b) 4] (a) Required arguments
ab

5. Functions that calls itself are known as (b) Keyword arguments


(a) User defined (b) Recursive (c) Default arguments
(c) Built- in (d) Lambda (d) Variable-length arguments
 [Ans. (b) Recursive]  [Ans. (a) Required arguments]
ur

6. Which of the following is not a type of function 15. In which of the following will invoke the
in python? functions after the parameters are recognized
(a) Control (b) Lambda by their parameters names?
(c) Recursion (d) Built in (a) Required arguments
.s

 [Ans. (a) Control] (b) Keyword arguments


7. Which of the following statement exits a (c) Default arguments
function?
(d) Variable-length arguments
w

(a) Exit (b) Def


 [Ans. (c) Default arguments]
(c) Return (d) None of these
16. Which arguments are used when more
 [Ans. (c) Return]
arguments are passed that have already been
w

8. In Python, statement in a block are written


specified?
with
(a) Keyword (b) Default
(a) Function (b) Identification
(c) Recursion (d) Parameters (c) Required (d) Variable-length
w

 [Ans. (b) Identification]  [Ans. (d) Variable-length]


9. Which of the following are treated as one big 17. Which of the following functions is an example
sequence of statement while exection? that supports variable-length arguments?
(a) Structure (b) Statement (a) While (b) If
(c) Block (d) Code (c) Print () (d) Input()
 [Ans. (c) Block]  [Ans. (c) Print ()]

86
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


18. Which function can take any number of 27. Defining a variable outside a function, its _ by
arguments and must return one value in the default.

Python Functions
form of an expression? (a) local (b) global
(a) user defined (b) recursive (c) function (d) operands
(c) lambda (d) default  [Ans. (b) global]
 [Ans. (c) lambda]

m
28. Write the output for the following code:
19. Which function is mostly used for creating c=1
small and one time anonymous function?
def add():
(a) Synchronous (b) Lambda
c=c+3

co
(c) User-defined (d) Built-in
 [Ans. (b) Lambda] print (c)
20. Predict the output of the following code add()
x = lambda y, z : y + z (a) 1 (b) 4
print (10,15) (c) 3 (d) error

s.
(a) 10 (b) 15  [Ans. (d) error]
(c) 25 (d) 1025 29. Write the output for the following code
 [Ans. (c) 25] a=5

ok
21. Which of the following statement causes your def add():
function to exit? a = 10
(a) break (b) pass add ()
(c) print (d) return print (a)
o
 [Ans. (d) return]
(a) 5 (b) 10
22. How many return statement is executed at
(c) 15 (d) error[Ans. (a) 5]
runtime?
ab

(a) 2 (b) 1 30. Write the output for the following code
(c) 3 (d) multiple a=5
 [Ans. (b) 1] def add ():
23. How many number of return statement a = 10
ur

allowed in a function definition? print (a)


(a) only one (b) only 2 add ()
(c) only 4 (d) multiple (a) 5 (b) 10
 [Ans. (d) multiple] (c) 15 (d) error
.s

24. Which of the following holds the current set of  [Ans. (b) 10]
variables and their values? 31. print (abs (-23.2)) displays
(a) scope (b) Identifiers
(a) –23 (b) –23.2
w

(c) operators (d) functions


 [Ans. (a) scope] (c) 23.2 (d) 0.2
25. How many types of scopes in Python?  [Ans. (c) 23.2]
w

(a) 3 (b) 4 32. print (ord(‘A’) displays


(c) 2 (d) many[Ans. (c) 2] (a) 65 (b) A (c) a (d) 97
26. What is the output for the following code  [Ans. (a) 65]
def loc() :
w

33. print (ord(‘a’) displays


y = “2”
loc() (a) 65 (b) A (c) –a (d) 97
print (y)  [Ans. (d) 97]
(a) loc() (b) 2 34. Print (chr(65)) displays
(c) y (d) error (a) 65 (b) A (c) a (d) c65
 [Ans. (d) error]  [Ans. (b) A]
87
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


35. print (chr(43)) displays 45. pow (5, 2) is equivalent to
(a) + (b) – (c) A (d) a (a) 5 * 2 (b) 5 * * 2
Unit II - Chapter 7

 [Ans. (a) +] (c) 2 * * 5 (d) 2 * 5


 [Ans. (b) 5 * * 2]
36. Print (bin(5)) displays
(a) 5 (b) 101 46. Which of the following function returns the

m
(c) 0b101 (d) 1010b computation of a * * b?
 [Ans. (c) 0b101] (a) pow () (b) id ()
(c) format () (d) type ()

co
37. Which function is inverse of chr () function?
 [Ans. (a) pow ()]
(a) type () (b) id ()
(c) formula () (d) ord () 47. Which of the following function returns the
 [Ans. (d) ord ()] smallest integer greater than or equal to x?

s.
38. Which function is an alternative to bin ()? (a) floor () (b) round ()
(a) id () (b) format () (c) pow () (d) ceil ()
(c) type () (d) chr ()  [Ans. (d) ceil ()]

ok
 [Ans. (b) format ()] Match the following
39. print (type (‘a’)) displays 1. i) round ( ) 1. nearest integer
(a) <class ‘char’> (b) <class ‘bool’> ii) sum ( ) 2. total value
o
(c) <class ‘slr’> (d) <class ‘string’> iii) id ( ) 3. identity of the object
 [Ans. (c) <class ‘slr’>] iv) type ( ) 4. type of the object
ab

40. Which of the following function return the


address of the object in memory? (i) (ii) (iii) (iv)
(a) address () (b) object () (a) 1 2 3 4
(c) id () (d) format () (b) 1 2 4 3
(c) 2 1 3 4
ur

 [Ans. (c) id ()]


(d) 2 1 4 3
41. print (format (25, ‘0’) displays
 [Ans. (a) (i)-1; (ii)-2; (iii)-3; (iv)-4]
(a) 25 (b) 025 (c) 31 (d) 031
2. i) Required 1. arguments is
.s

 [Ans. (c) 31]


Arguments improper order
42. The default presidium of fixed point constant ii) Keyword 2. asterisk symbol
is Arguments
w

(a) 7 (b) 6 (c) 8 (d) 16 iii) Default 3. Correct Positional


 [Ans. (b) 6] arguments order
43. print (format (14, ‘f ’) displays iv) Variable length 4. default value
w

(a) 14.00 (b) 14 arguments


(c) 14.0000 (d) 14.000000
(i) (ii) (iii) (iv)
 [Ans. (d) 14.000000]
w

(a) 1 2 3 4
44. print (round (17.89, 1) displays (b) 4 3 2 1
(a) 18 (b) 181 (c) 3 1 4 2
(c) 17.9 (d) 18.0 (d) 4 2 1 3
 [Ans. (c) 17.9]  [Ans. (c) (i)-1; (ii)-2; (iii)-3; (iv)-4]

88
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose odd man out 6. Python _________ should not be used as
function name.

Python Functions
1. (a) User defined (b) Built in
(a) Identifiers (b) Operators
(c) Recursion (d) Parameters (c) Variables (d) Keywords
 [Ans. (d) Parameters]  [Ans. (d) Keywords]

m
2. (a) filter ( ) (b) map ( ) 7. While defining syntax, the text which is given
(c) print ( ) (d) reduce ( ) in _________ is optional
(a) () (b) <> (c) [] (d) {}
 [Ans. (c) print ( )]
 [Ans. (c) []]

co
3. (a) ceil ( ) (b) floor ( ) 8. A block within a block is called ________block.
(c) type ( ) (d) round ( ) (a) Nested (b) Compressed
 [Ans. (c) type ( )] (c) Control (d) Called
4. (a) min ( ) (b) max ( )  [Ans. (a) Nested]

s.
(c) round ( ) (d) bin ( ) 9. If there is no return statement present inside
 [Ans. (d) bin ( )] the function, then the function will return _
_____ object.

ok
5. (a) ord ( ) (b) chr ( )
(a) No (b) Nothing
(c) id ( ) (d) bin ( ) (c) None (d) def
 [Ans. (c) id ( )]  [Ans. (c) None]
Choose and fill in the blanks
o
10. ______of variable refers to the part of the
1. _______ makes your program easier to write, program, where it is accessible.
read, test and fix errors. (a) return (b) scope
ab

(a) Functions (b) List (c) definition (d) argument


(c) Tuples (d) Loops  [Ans. (b) scope]
 [Ans. (a) Functions]
11. A_____ variable declared inside the function’s
2. A group of related statement that perform a body is known as
ur

specific task is called as ____________ (a) file scope (b) function scope
(a) Lists (b) Tuples
(c) global scope (d) local scope
(c) Control statements (d) Functions
 [Ans. (d) local scope]
 [Ans. (d) Functions]
.s

3. Functions that are anonymous in named 12. The _____arguments are also local to function
function are called ____________ (a) default (b) keyword
(a) User defined (b) Built-in (c) format (d) variable-length
w

(c) Lambda (d) Recursive  [Ans. (c) format]


 [Ans. (c) Lambda] 13. ________ helps us to define a program into
modules.
w

4. Function blocks begins with the keyword


(a) Functions (b) Sub programs
_________
(a) Fun (b) Definition (c) Routines (d) Recursion
 [Ans. (a) Functions]
w

(c) Def (d) Function


 [Ans. (c) Def] 14. _________ are variables used in the function
5. Functions identified by function name and definition
__________ (a) Arguments (b) Identifiers
(a) [] (b) () (c) {} (d) <> (c) Structures (d) Parameters
 [Ans. (b) ()]  [Ans. (d) Parameters]

89
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


15. In ___________ arguments, one can put 23. The _____ function is inverse of ord () function.
arguments in improper order. (a) id () (b) bin ()
Unit II - Chapter 7

(a) Default (b) Keyword (c) chr () (d) none of these


(c) Required  [Ans. (c) chr ()]
(d) Variable length arguments 24. _______ works like loop.
(a) Function (b) Recursion

m
 [Ans. (b) Keyword]
(c) Composition (d) Specification
16. In python the _________ arguments is an
 [Ans. (b) Recursion]
arguments that takes a default values if no
value is provide in function call 25. You can convert any loop to _____.

co
(a) Default (b) Keyword (a) Recursion (b) Composition
(c) Required (c) Function (d) Branching
(d) Variable length arguments  [Ans. (a) Recursion]
 [Ans. (a) Default] 26. ______ is applied in any recursive function is

s.
known as base condition.
17. In variable length arguments we can pass the (a) Finite iteration
arguments using ______ methods. (b) Default arguments

ok
(a) Three (b) Four (c) Keyword arguments
(c) Two (d) Six (d) Infinite iteration
 [Ans. (c) Two]  [Ans. (d) Infinite iteration]

18. When a variable is created inside the ______, 27. ______ function returns the largest integer
less than or equal to x.
o
the variable becomes local to it.
(a) cell () (b) floor ()
(a) program (b) function (c) pow () (d) round ()
(c) block (d) global
ab

 [Ans. (b) floor ()]


 [Ans. (b) function]
Consider the following statement
19. A____ variable only exists while the function
is executing. 1. Assertion : In keyword arguments user can also
put arguments in improper order.
ur

(a) global (b) local


(c) file (d) function  Reason : The value of the keyword argument
is matched with the parameter name.
 [Ans. (b) local]
(a) A & R is True
20. _________ function can only access global
.s

(b) A & R is False


variables. (c) A is True R is False
(a) user-defined (b) anonymous (d) A is false and R is True
(c) recursive (d) return  [Ans. (d) A & R is True]
w

 [Ans. (b) anonymous]


Choose the correct pair
21. In python _________ function is a function
1. a) User-defined that are inbuilt with in
w

that is defined without a name.


function python
(a) Anonymous (b) Recursive
(c) User defined (d) Default b) Built – in defines by the user
functions themselves.
w

 [Ans. (a) Anonymous]


c) Lambda that are anonymous
22. The ______ keyword used to read and write a functions un-named functions
global variable inside a function. d) Recursive that calls next function
(a) global (b) local function to execute
(c) return (d) def
[Ans. (c) Lambda functions – that are
 [Ans. (a) global]  anonymous un-named functions]

90
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Function Output Choose the incorrect statement

Python Functions
a) print (math.floor –24 1. (a) F  unctions avoids repetion and makes with
(–23.2)) degree of code using .
b) print (math, ceil –24 (b) Functions does not provide better
modularity for python application
(–23.2))

m
(c) Recursive functions are the functions which
c) print (ord (97)) a calls itself
d) print (char (A)) 65 (d) A group of related statement that perform a
specific task called functions.
 [Ans. (a) print (math.floor (-23.2)) =-24]

co
 [Ans. (b) Functions does not provide better
 modularity for python application]
Choose the incorrect pair 2. (i) Non –keyword variable arguments are called
1. Function Output dictionaries
a) print (type (True)) <class ‘bool’> (ii) Variable – length arguments can be defined

s.
using *.
b) print (bin (5)) 101
(iii) Lambda keyword is used to define
c) print (format (5, ‘b’) 101 anonymous function

ok
d) print (math.ceil (-23.2) –23 (iv) Anonymous function is a function that must
be defined with a name.
 [Ans. (b) print (bin (5)) - 101] (a) I and II (b) II and III
2. a) abs ( ) absolute value (c) I, II and IV (d) I and IV
b) ord ( ) inverse of chr( )  [Ans. (d) I and IV]
o
c) chr ( ) inverse of ord ( )
3. (i) A  variable defined within a block can be
d) bin ( ) minimum value accessed outside a function also.
ab

 [Ans. (d) bin ( ) - minimum value] (ii) Local variable only exits while the function
is executing.
Choose the correct statement (iii) a variable defined outside a function, its
1. (i) L  ambda function is not used for creating global by default.
ur

small and one time anonymous function. (iv) local keyword is used to read and write local
(ii) Lambda function is a function defined variable inside a function.
without a name. (a) i and ii (b) iii and iv
(iii) Lambda function is also called Synchronous (c) ii and iii (d) i and iv
.s

function.  [Ans. (d) i and iv]


(iv) Lambda function must return one value in
the form of an expression. 4. (a) Required arguments are the arguments
passed to a function in correct positional
w

(a) i and iii (b) ii and iii


(c) iii and iv (d) only i order
 [Ans. (a) i and iii] (b) Keyword arguments will not invoke the
2. (i) The return statement causes your function function after the parameters are recognized
w

to exit. by their parameter names.


(ii) The return statement returns value to its (c) A python function allows us to give the
caller default values for parameters in the function
w

(iii) Any number of return statements are definition.


allowed (d) Variable length arguments are not specified
(iv) Only one return is executed at runtime in the function’s definition.
(a) i and ii (b) i, iii and iv [Ans. (b) Keyword arguments will not invoke
(c) ii and iv (d) ii and iii the function after the parameters
(e) all of these [Ans. (e) all of these] are recognized by their parameter
names.]

91
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Very Short Answers 2 MARKS 9. What are the methods used to parse the
arguments to the variable length arguments?
Unit II - Chapter 7

1. How the statements in a black are written in


Ans. In Variable Length arguments we can parse the
python?
arguments using two methods.
Ans. In Python, statements in a block are written with
(i) Non keyword variable arguments
indentation.

m
(ii) Keyword variable arguments
2. What is meant by block in python? 10. What are called tuples?
Ans. A block is one or more lines of code, grouped Ans. Non-keyword variable arguments are called

co
together so that they are treated as one big tuples.
sequence of statements while execution.
11. How the value returned from lambda function?
3. How the nested block are indented?
Ans. Lambda function can take any number of
Ans. A block within a block is called nested block. arguments and must return one value in the
When the first block statement is indented by a

s.
form of an expression.
single table space, the second block of statement 12. Write the output for the following program.
is indented by double tab spaces.
Ans. z = lamda x, y:x//y
4. Write the output of the following program.

ok
print (z (10, 3))
Ans. Example :
Output : 3
def hello():
13. What is local variable?
print (“hello - Python”)
Ans. A variable declared inside the function's body or
return
o
in the local scope is known as local variable.
print (hello()) 14. Write the output for the following.
Output:
ab

(i) Print (ord (‘a’))


hello – Python (ii) Print (chr (65))
None
(iii) Print (bin (15))
5. Differentiate parameters and arguments.
(iv) Print (format (15, ‘b’))
ur

Ans. Parameters are the variables used in the function


Ans.
definition whereas arguments are the values we
(i) 97
pass to the function parameters.
(ii) A
6. Write the syntax for passing arguments to
(iii) ob 1111
.s

functions.
(iv) 1111
Ans. syntax :
def function_name (parameter(s) separated by Short Answers 3 MARKS
w

comma): 1. When do you call the function to perform a


7. Write the output for the following program specify task?
Ans. def display (a, b): Ans. (i) When you want to perform a particular task
w

return a * * b that you have defined in a function, you call


the name of the function responsible for it.
print (area (2, 5)
(ii) If you need to perform that task multiple
Output : 32
w

times throughout your program, you don’t


8. What are arguments? What are the types? need to type all the code for the same task
Ans. Arguments are used to call a function and again and again.
there are primarily 4 types of functions. They (iii) You just call the function dedicated to
are: Required arguments, Keyword arguments, handling that task, and the call tells Python
Default arguments and Variable-length to run the code inside the function.
arguments.

92
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Write the advantages of user – defined 5. How python takes a default value in the
functions. function call? Explain with an example.

Python Functions
Ans. Advanntages of User-defined Functions Ans. (i) In Python the default argument is an
(i) Functions help us to divide a program into argument that takes a default value if no
modules. This makes the code easier to value is provided in the function call.
manage. (ii) The following example uses default

m
(ii) It implements code reuse. Every time you arguments, that prints default salary when
need to execute a sequence of statements, no argument is passed.
all you need to do is to call the function. (iii) Example :
(iii) Functions, allows us to change functionality

co
def printinfo( name, salary = 3500):
easily, and different programmers can work
print (“Name: “, name)
on different functions.
3. Write a note on “Required arguments”. print (“Salary: “, salary)
Ans. (i) “Required Arguments” are the arguments return
passed to a function in correct positional printinfo(“Mani”)

s.
order. Here, the number of arguments in When the above code is executed, it
the function call should match exactly with produces the following output
the function definition. Output:

ok
(ii) Atleast one parameter to prevent syntax Name: Mani
errors to get the required output. Salary: 3500
(iii) Example : When the above code is changed as print
def printstring(str): info(“Ram”,2000) it produces the following
print ("Example - Required  arguments") output:
o
print (str) Output:
return Name: Ram
# Now you can call printstring() function
ab

Salary: 2000
printstring ("Welcome")
Output: 6. When the variable – length arguments are
Example - Required arguments used? Explain with an example.
Welcome Ans. (i) Syntax - Variable-Length Arguments :
def function_name(*args):
ur

4. How will you invoke the function after the


parameters are recognized by their parameter function_body
names? Explain with an example. return_statement
Ans. (i) Keyword arguments will invoke the function (ii) Example :
.s

after the parameters are recognized by their def printnos (*nos):


parameter names. for n in nos:
(ii) The value of the keyword argument is print(n)
matched with the parameter name and so,
w

return
one can also put arguments in improper
order. # now invoking the printnos() function
(iii) Example : print ('Printing two values')
def printdata (name): printnos (1,2)
w

print (“Example-1 Keyword arguments”) print ('Printing three values')


print (“Name :”,name) printnos (10,20,30)
return Output:
w

# Now you can call printdata() function Printing two values


printdata(name = “Gshan”) 1
When the above code is executed, it 2
produces the following output : Printing three values
Output: 10
Example-1 Keyword arguments 20
Name :Gshan 30
93
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


7. Write a note of return statement. Output :
Ans. The return Statement : Inside add() function x value is : 5
Unit II - Chapter 7

(i)  The return statement causes your function In main x value is : 5


to exit and returns a value to its caller. The 9. Explain with an example how will you use
point of functions in general is to take global and local variables in the same code.
inputs and return something.

m
Ans. Using Global and Local variables in same
(ii) The return statement is used when a function code :
is ready to return a value to its caller. So, x=8 # x is a global variable
only one return statement is executed at def loc():

co
run time even though the function contains global x
multiple return statements. y = "local"
(iii) 
Any number of 'return' statements are x=x*2
allowed in a function definition but only print(x)

s.
one of them is executed at run time. print(y)
loc()
8. What is the use of global keyword? Explain
Output :
with an example?

ok
16
Ans. The global keyword are used modify the global
local
variable inside the function.
 Changing Global Variable From Inside a 10. Explain how will you use global and local
variable with same name.
Function using global keyword.
o
Ans. x = 5
x = 0 # global variable
def loc():
def add():
ab

x = 10
global x
print ("local x:", x)
x=x+5 # increment by 2
loc()
print ("Inside add() function x value is :", x)
print ("global x:", x)
add()
ur

Output :
print ("In main x value is :", x)
local x: 10
global x: 5
.s

11. Write a note on (i) min (), (ii) max (), (iii) sum ().
Ans.
S.No. Function Description Syntax Example
w

(i) min ( ) Returns the minimum min (list) MyList = [21,76,98,23]


value in a list. print ('Minimum of MyList :', min (MyList))
Output :
w

Minimum of MyList : 21
(ii) max ( ) Returns the maximum max (list) MyList = [21,76,98,23]
value in a list. print ('Maximum of MyList :', max (MyList))
w

Output :
Maximum of MyList : 98
(iii) sum ( ) Returns the sum of sum (list) MyList = [21,76,98,23]
values in a list. print ('Sum of MyList :', sum (MyList))
Output :
Sum of MyList : 218

94
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


12. Write a note on (i) floor (), (ii) ceil (), (iii) Sprt ().
Ans.

Python Functions
Function Description Syntax Example
floor ( ) Returns the largest integer less math.floor (x) x=26.7
than or equal to x print (math.floor (x))

m
Output :
26
ceil ( ) Returns the smallest integer math.ceil (x) x= 26.7

co
greater than or equal to x print (math.ceil (x))
Output :
27
sqrt ( ) Returns the square root of x sqrt (x ) b= 49

s.
Note: x must be greater than print (math.sqrt (b))
0 (zero) Output :
7.0

Long Answers
1. Write a python program to find HCF of two
numbers using recursion.
o ok
5 MARKS 2. Write a python program to find Fibonacci
series of n terms using recursion.
Ans. # program to find fibonacci series
def fibo (n):
Ans. # python program to find HCF
ab

def HCF (x, y): if n < = 1:


if (x > y): return n
s=y
else:
else:
return (fibo (n - 1) + fibo (n - 2))
ur

s=x
for I inrange (1, s + 1): n = int (input (“Enter How manu terms”))
if ((x % I = = 0) and (y % i = = 0)): for i in range (n):
hcf = i
.s

print (fibo (i))


return hcf
x = int (input (“Enter Number 1”))
w

y = int (input (“Enter Number 2”))


print (HCF (x, y))
w


w

95
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

  
STRINGS AND

8
Chapter
STRING MANIPULATION

m
CHAPTER SNAPSHOT

co
8.1 Introduction 8.6 String Formatting Operators
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

s.
8.5 String Operators 8.10 Membership Operators

Evaluation 5. Strings in python:

ok
(a) Changeable (b) Mutable
(c) Immutable (d) flexible
Part - I
 [Ans. (c) Immutable]
Choose the best answer  (1 mark) 6. Which of the following is the slicing operator?
o
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]
(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"
 [Ans. (d) third argument of slice operation]
.s

str1[7] = "-"
8. Which of the following formatting character
(a) Chennai-Schools (b) Chenna-School is used to print exponential notation in upper
(c) Type error (D) Chennai case? [PTA-5]
w

 [Ans. (c) Type error] (a) %e (b) %E (c) %g (d) %n


3. Which of the following operator is used for  [Ans. (b) %E]
concatenation? 9. Which of the following is used as placeholders
w

or replacement fields which get replaced along


(a) + (b) & (c) * (d) =
with format( ) function? [PTA-4]
 [Ans. (a) +]
(a) { } (b) < > (c) ++ (d) ^^
w

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)]

[96]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Part - II (ii) Thus, [] is also known as slicing operator.

Strings and String Manipulation


Using slice operator, you have to slice one
Answer the following questions or more substrings from a main string.
 (2 marks) General format of slice operation :
Str[start : end]
1. What is String?
Part - III

m
Ans. (i) String is a data type in python, which is
used to handle array of characters. Answer the following questions
(ii) String is a sequence of Unicode characters
that may be a combination of letters,  (3 marks)

co
numbers, or special symbols enclosed 1. Write a Python program to display the given
within single, double or even triple quotes. pattern. [Govt. MQP-2019]
(iii) Example : COMPUTER
'Welcome to learning Python' COMPUTE
"Welcome to learning Python" COMPUT

s.
COMPU
" "Welcome to learning Python" " COMP
2. Do you modify a string in Python? COM
Ans. (i) Yes we can modify the string by the CO

ok
following method. C
(ii) A new string value can be assign to the Ans. str1 = "COMPUTER"
existing string variable. index = len(str1)
(iii) When defining a new string value to the for i in str1:
existing string variable.
o
print (str1[: index])
(iv) Python completely overwrite new string on
index – = 1
the existing string.
ab

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

>>> str1="How about you" Descrip


>>> print (str1) Syntax Example
tion
How about you
(a) capitalize( ) Used to >>> city="chennai"
>>> del str1
capitalize >>> print(city.
.s

>>> print (str1)


the first capitalize())
Traceback (most recent call last):
character Chennai
File "<pyshell#14>", line 1, in <module>
of the
w

print (str1)
NameError: name 'str1' is not defined string
(b) swapcase( ) It will >>> str1="tAmiL
4. What will be the output of the following
change NaDu"
w

python code?
case of >>> print(str1.
str1 = "School"
every swapcase())
print(str1*3)
character TaMIl nAdU
w

Ans. Output : School School School


to its
5. What is slicing? [PTA-6] opposite
Ans. (i) Slice is a substring of a main string. A case vice-
substring can be taken from the original
versa.
string by using [] operator and index or
subscript values.

97
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. What will be the output of the given python Part - IV
program?
Answer the following questions
Unit II - Chapter 8

str1 = "welcome"
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]

m
Ans. weol Ans. String Operators : Python provides the
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

co
Ans. (i) The format( ) function used with strings is strings is called as Concatenation. The plus
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"

s.
along with format( ) function. 'welcomePython'
(iii) Example : (ii) Append (+ =) : Adding more strings at
num1=int (input("Number 1: ")) the end of an existing string is known as

ok
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 : >>> str1="Welcome to "
Number 1: 34 >>> str1+="Learn Python"
o
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 "
count Returns the >>> str1="Raja Raja
ur

>>> 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.
■ Using slice operator, you have to slice one
w

that substring 0
or more substrings from a main string.
may be a single >>> print(str1.
General format of slice operation :
character. count('R')) str[start:end]
Range (beg 2
w

■ Where start is the beginning index and


and end) >>> print(str1. end is the last index value of a character in
arguments count('a')) the string.
are optional. 5 ■ Python takes the end value less than one
w

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

98
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(v) Stride when slicing string : wrapped=textwrap.fill(text_without_

Strings and String Manipulation


■ When the slicing operation, you can specify  Indentation, width=50)
a third argument as the stride, which refers print(textwrap.indent(wrapped, '*')
to the number of characters to move print ( )
forward after the first character is retrieved Output :
from the string. * Strings are immutable. Slice is a

m
■ The default value of stride is 1. * substring of a main string. Stride
■ Python takes the last value as n-1. * is a third argument in slicing operation
■ You can also use negative value as stride, to 4. Write a program to print integers with ‘*’ on
prints data in reverse order.

co
the right of specified width.
Example : Ans. x = 1 2 3
>>>str1="Welcome to learn Python" print("original number:", x)
>>>print (str1[10:16]) print("formatted number(right padding, width
>>>print (str1[::-2])  6) : "+" {:*<7d}".format(x));

s.
Output : Output :
Learn original number : 1 2 3
nhy re teolW formatted number(right padding, width 6):
 1 2 3 ***

ok
5. Write a program to create a mirror of the given
Hands on Experience string. For example, "wel" = "lew".
1. Write a python program to find the length of Ans. str1= input (“Enter a string”)
a string. str2 = ‘ ‘
Ans. str = input ("Enter a string") index = -1
o
print (len(str)) for i in str1:
Output : str2 = str1[index]
ab

Enter a string : HELLO index - = 1


5 print (“The given string = { } \n The Reversed string
2. Write a program to count the occurrences of = { }".format(str1, str2))
each word in a given string. Output :
Ans. def word_conunt(str): Enter a string : welcome
ur

counts=dict() The given string = welcome


words=str.split() The Reversed string = emoclew
for word in words: 6. Write a program to removes all the occurrences
if word in counts: of a give character in a string.
.s

counts[word]+=1 Ans. def removechar(s,c):


else: # find total no of occurrence of a character
counts[word]=1 counts = s.count(c)
return counts
w

# convert into list of characters


print(word_count('the quick brown fox jumps
over the lazy dog.')) s = list(s)
Output : # keep looping until counts become 0
w

{'th' :2, jumps' : 1, 'brown' : 1, 'lazy' : 1, 'fox' : while counts :


 1, 'over' : 1, 'quick' : 1, 'dog' : 1} # remove char. from list
3. Write a program to add a prefix text to all the s.remove(c)
lines in a string. counts – = 1
w

Ans. import textwrap # join remaining characters


text = s = ".join(s)
""Strings are immutable. Slice is a substring print(s)
of a main string. Stride is a third argument s = "Python programming"
in slicing operation"" remove char(s, 'p')
text_without_Indentation = textwrap. Output :
dedent(text) ython rogramming
99
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


7. Write a program to append a string to another 10. Write a program to count the number of
string without using += operator. characters, words and lines in a given string.
Unit II - Chapter 8

Ans. s1 = input (“Enter first string :”) Ans. string = input (“Enter string :”)
s2 = input (“Enter second string :”) char = 0
print('concatenated strings =', " ".join([s1,s2])) word = 0
Output : line = 0

m
for i in string :
Enter the first string : Tamil
char = char + 1
Enter the second string : Nadu if(i = = ‘ ‘) :
concatenated strings = Tamil Nadu

co
word = word + 1
8. Write a program to swap two strings. elifi(i = ='\n'):
Ans. print(“Enter 'x' for exit.") line = line + 1
string1 = input("Enter first string :") print (“Number of words in the string :"))
print (word)
if string1 = = 'x':

s.
print (“Number of characters in the string :")
exit(); print(char)
else: print("Number of lines in the string :")
string2=input("Enter second string :")

ok
print(line)
print("\n Both strings before swap : ") Output :
print("First string =", string1) Enter string : weclome to learning python
print ("Second string = ", string2) Number of words in the string : 4
temp = string1 Number of characters in the string : 26
o
string1 = string2 Number of lines in the string : 1
string2 = temp PTA Questions and Answers
ab

print(“\n Both strings after swap :”)


print("First string =", string1) 1 MARK
print("Second string =", string2)
1. Which command can be used to remove entire
Output :
string variable in Python? [PTA-3]
ur

Enter 'x' for exit


(a) rem (b) remove
Enter first string : code
(c) del (d) delete
Enter second string : python
[Ans. (c) del]
Both strings before swap:
.s

First string = code 2. What will be the output of the following


Second string = python snippet? [PTA-6]
Both strings after swap: str1="COMPUTER"
w

First string = python print(str1[::2])


Second string = code (a) ER (b) CO
(c) OPTR (d) CMUE
9. Write a program to replace a string with
w

another string without using replace(). [Ans. (c) OPTR]


Ans. s1 = input (“Enter the string to be replaced :”) 2 MARKS
s2 = input (“Enter string to replace with”)
w

1. What will be the output of the following


s1 = s2
Python code? [PTA-1]
print("Replaced strings is :, sl)
Str1 = "Madurai"
Output :
Enter the string to be replaced : Computer print(Str1*3)
Enter the string to replace with : repcomputer Ans. Output :
Replaced string is repcomputer Madurai Madurai Madurai

100
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. What are membership operators in Python? Write a short note on string slicing with syntax

Strings and String Manipulation


Ans. Membership Operators :  [PTA-2]
and example. [Govt. MQP-2019; PTA-3]
Ans. Slice is a substring of a main string. A substring
(i) The ‘in’ and ‘not in’ operators can be used
can be taken from the original string by using
with strings to determine whether a string [] operator and index or subscript values. Thus,
is present in another string. Therefore, [] is also known as slicing operator. Using slice

m
these operators are called as Membership operator, you have to slice one or more substrings
Operators. from a main string.
(ii) Example : General format of slice operation:

co
str[start:end]
str1=input ("Enter a string: ")
Where start is the beginning index and end is
str2="chennai" the last index value of a character in the string.
if str2 in str1: Python takes the end value less than one from
print ("Found") the actual index specified. For example, if you

s.
want to slice first 4 characters from a string,
else: you have to specify it as 0 to 5. Because, python
print ("Not Found") consider only the end value as n-1.
Example : slice a single character from a string

ok
(iii) Output : 1
>>> str1="THIRUKKURAL"
Enter a string: Chennai GHSS, Saidapet
>>> print (str1[0])
Found T
(iv) Output : 2
2. What will be the output of the following
o
Enter a string: Govt GHSS, Ashok Nagar Python program? [PTA-4]
Not Found str1 = "welcome"
ab

str2 = "to school"


3. What will be the output of the following
str3 = str1[:3]+str2[len(str2)-1:]
Python snippet? [PTA-4]
print(str3)
str1="THOLKAPPIYAM"
Ans. Output :
print(str1([4:])
ur

weol
print(str1[4::2])
3. How index value allocated to each character of
print(str1[::3]) a string in Python? [PTA-5]
print(str1[::–3]) Ans. (i) Once you define a string, python allocate
.s

Ans. Output : an index value for its each character.


These index values are otherwise called
THOLKAPPIYAM
as subscript which are used to access and
w

4. What is the positive and negative subscript manipulate the strings. The subscript can
value of the character 'h' in string 'school'? be positive or negative integer numbers.
 [PTA-5] (ii) The positive subscript 0 is assigned to the
w

first character and n-1 to the last character,


Ans. Positive value = 2
where n is the number of characters in the
Negative value = –4 string. The negative index assigned from
the last character to the first character in
w

3 MARKS reverse order begins with -1.


Example :
1. What is the use of the operator += in Python
String S C H O O L
string operation?
(or) Positive subscript 0 1 2 3 4 5
Negative subscript –6 –5 –4 –3 –2 –1

101
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. Write a note on string formatting operators of 5. Explain about slicing and slicing with stride.
Python. [PTA-6]  [PTA-6]
Unit II - Chapter 8

Ans. The string formatting operator is one of the Ans. (i) Slice is a substring of a main string. A
most exciting feature of python. The formatting substring can be taken from the original
operator % is used to construct strings, replacing string by using [] operator and index or
parts of the strings with the datastored in subscript values.

m
variables. (ii) Thus, [] is also known as slicing operator.
Syntax: Using slice operator, you have to slice one
(“String to be display with %val1 and %val2” or more substrings from a main string.
 %(val1, val2)) General format of slice operation :

co
Example : Str[start : end]
name = "Rajarajan" When the slicing operation, you can specify a
mark = 98 third argument as the stride, which refers to the
print ("Name: %s and Marks: %d" %(name,mark)) number of characters to move forward after the
Output : first character is retrieved from the string. The

s.
Name: Rajarajan and Marks: 98 default value of stride is 1.

ok
5 MARKS
1. Write the short note on the following built-in string functions. [PTA-3]
(i) capitalize() (ii) isalpha()
o
(iii) isalnum() (iv) lower()
Ans.
ab

Syntax Description Example

capitalize( ) Used to capitalize the first >>> city="chennai"


character of the string >>> print(city. capitalize())
Chennai
ur

isalpha( ) Returns True if the string >>>’Click123’.isalpha()


contains only letters. False
Otherwise return False. >>>’python’.isalpha()
.s

True
isalnum( ) Returns True if the string contains only >>>str1=’Save Earth’
letters and >>>str1.isalnum()
w

digit. It returns False. If the string False


contains any special character like _, The function returns False as space
@,#, *, etc.
is an alphanumeric character.
w

>>>’Save1Earth’.isalnum()
True
lower( ) Returns the exact copy >>>str1=’SAVE EARTH’
w

of the string with all the >>>print(str1.lower())


letters in lowercase. save earth

102
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Explain the following string functions with suitable examples. [Govt. MQP-2019; PTA- 4 , 5]

Strings and String Manipulation


(i) center() (ii) find()
Ans.
Syntax Description Example
center(width, fillchar) Returns a string with the >>> str1="Welcome"

m
original string centered to a >>> print(str1.center(15,'*') )
total of width columns and ****Welcome****
filled with fillchar in columns
that do not have characters

co
find(sub[, start[, end]]) The function is used to >>>str1=’mammals’
search the first occurrence >>>str1.find(‘ma’)
of the sub string in the given 0
string. It returns the index at On omitting the start parameters, the function

s.
which the substring starts. It starts the search from the beginning.
returns -1 if the substring does >>>str1.find(‘ma’,2)
not occur in the string. 3
>>>str1.find(‘ma’,2,4)

ok
-1
Displays -1 because the substring could not be
found between the index 2 and 4-1.
>>>str1.find(‘ma’,2,5)
o
Government Exam Questions and Answers 3 MARKS
ab

1 MARK 1. Write the output for the following program


 [QY-2019]
1. The positive and negative index values of 'P' in str="COMPUTER"
the string Str1='COMPUTER' are [Govt.
index=0
MQP-2019]
for i in str:
ur

(a) 3, –4 (b) 4, –4
print(str[: index+1])
(c) 3, –5 (d) 4, –5
index +=1
[Ans. (c) 3, –5]
Ans. Output :
2 MARKS
.s

C
1. What will be the output of the following C O
Python Code? [HY-2019] C O M
w

str="Chennai" C O M P
print(str*4) C O M P U
Ans. Output : Chennai Chennai Chennai Chennai C O M P U T
w

2. Explain the following function. [QY-2019] C O M P U T E


Ans. C O M P U T E R
5 MARKS
w

Syntax Description Example


1. Write a python program to check whether the
lower( ) Returns the >>>str1=’SAVE EARTH’
exact copy given string is palindrome or not. [QY-2019]
>>>print(str1.lower())
of the string Ans. str1 = input ("Enter a string: ")
save earth
with all the str2 = ' '
letters in index=-1
lowercase.

103
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


for i in str1: 7. The positive subscript always starts with
str2 += str1[index] (a) 0 (b) 1 (c) –1 (d) 0.1
Unit II - Chapter 8

index -= 1  [Ans. (a) 0]


print ("The given string = { } \n The Reversed 8. The negative subscript is always begins with
 string = { }".format(str1, str2)) (a) 0 (b) 1
(c) –1 (d) –1.0

m
if (str1==str2):
print ("Hence, the given string is   [Ans. (c) –1]
Palindrome") 9. What is the output for the following
else: >>> s1 = "how"

co
>>>s1[0] = ‘A’
print ("Hence, the given is not a
(a) How (b) A
palindrome")
(c) Aow (d) Error
additional questions and Answers  [Ans. (d) Error]

s.
10. Which of the following operators are useful to
Choose the Correct Answer 1 MARK do string manipulation?
1. Which of the following is used to handle array (a) +, - (b)*, / (c) + * (d)’, "
 [Ans. (c) + *]

ok
of characters in python?
(a) Functions (b) Composition 11. Adding more strings at the end of an existing
(c) String (d) Arguments string is known as
 [Ans. (c) String] (a) Con cat (b) Con catenation
(c) Join (d) Append
2. String are enclosed with
o
 [Ans. (d) Append]
(a) " (b) " " 12. A substring can be taken from the original
(c) '''''' '''''' (d) ''' ''' string by using
ab

(e) all of these [Ans. (e) all of these]


(a) { } (b) ( ) (c) [ ] (d) < >
3. Which of the following allows creation of  [Ans. (c) [ ]]
multiline strings 13. What is the output from the following
(a) ' ' (b) '' '' statement?
ur

(c) '''''' '''''' (d) none of these str1 = "welcome"


(e) None of these  [Ans. (c) '''''' ''''''] print (str1[: : 3]
4. Find the output for the following (a) come (b) ome
print (‘Greater Chennai cooperation’s
 (c) wce (d) wel
.s

student’)  [Ans. (c) wce]


(a) Greater Chennai Corporation’s student 14. What is the output from the following
(b) Greater Chennai Corporation statement?
w

(c) S Student str1 = "python"


(d) Error : Invalid Syntax print (str1 [: : - 2])
 [Ans. (d) Error : Invalid Syntax] (a) nhy (b) Pyt (c) hy (d) on
w

 [Ans. (a) nhy]


5. String index values are also called as 15. Which of the following operator is used to
(a) class (b) function construct strings?
(c) subscript (d) arguments (a) : (b) % (c) : : (d) #
w

 [Ans. (c) subscript]  [Ans. (b) %]


6. Which of the following is used to access and 16. Which of the following formatting operator is
manipulate the strings? used to represent signed decimal integer?
(a) Index value (b) Subscript (a) % d or % i (b) %s or % c
(c) Argument (d) Parameters (c) %g or % x (d) %s or % e
(e) a or b [Ans. (e) a or b]  [Ans. (a) % d or % i]

104
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


17. Escape sequences starts with a 28. Which function returns the number of substrings

Strings and String Manipulation


(a) / (b) \ (c) // (d) \" occurs within the given range?
 [Ans. (b) \] (a) return () (b) count ()
(c) substring () (d) range ()
18. What is Escape sequence character for the
description character with octal value?  [Ans. (b) count ()]
(a) \OHH (b) \OOO 29. The default value of stride is

m
(c) /OOO (d) /OHH (a) 0 (b) – 1 (c) 1 (d) – 0
 [Ans. (b) \OOO]  [Ans. (c) 1]
19. Which of the following is used as a place Match the following

co
holders which get replaced along with format
function? 1. (i) %i (1) short number in
(a) [ ] (b) ( ) (c) { } (d) < > exponential form
 [Ans. (c) { }] (ii) % 0 (2) exponential notation
20. The function returns the length of the string (iii) % G (3) signed decimal integer

s.
in python is
(a) length ( ) (b) leng ( ) (iv) % X (4) octal integer
(c) len ( ) (d) strlrn ( ) (v) % E (5) hexadecimal integer

ok
 [Ans. (c) len ( )]
(a) 3, 4, 5, 1, 2 (b) 3, 4, 1, 2, 5
21. What will be the output of print (c) 3, 1, 4, 5 2 (d) 3, 4, 1, 5, 2
(len("CHENNAI"))?
(a) 7 (b) 8  [Ans. (d) 3, 4, 1, 5, 2]
(c) 9 (d) Error[Ans. (a) 7] 2. (i) \a (1) line feed
o
22. Which of the following function used to (ii) \b (2) Backspace
capitalize the first character of the string? (iii) \f (3) Horizontal Tab
ab

(a) captial ( ) (b) firstcapital ( )


(c) capitalize ( ) (d) capitalizefirst ( ) (iv) \n (4) Bell
 [Ans. (c) capitalize ( )] (v) \t (5) Form feed
23. The function used to search the first occurrence (a) 2, 4, 5, 1, 3 (b) 4, 2, 5, 3, 1
of the substring in the given string is
ur

(c) 4, 2, 5, 3, 1 (d) 4, 5, 2, 1, 3
(a) search ( ) (b) find ( )  [Ans. (c) 4, 2, 5, 3, 1]
(c) find string ( ) (d) searchstring ( )
 [Ans. (b) find ( )] Choose and fill in the blanks
.s

24. What is the output for the following? 1. __________________ is a combination of


‘mammals’. find (‘ma’) letters, numbers or special symbols enclosed
(a) 0 (b) 1 (c) –1 (d) 3 with. ", " " or ''' '''
 [Ans. (a) 0] (a) String (b) Function
w

25. What is the output for the following? (c) Parameters (d) Scope fo aviable
‘mammals’. find (‘ma’, 2)
 [Ans. (a) String]
(a) 0 (b) 1 (c) –1 (d) 3
2. In python ____________ are immutable.
w

 [Ans. (d) 3]
(a) Characters (b) Strings
26. What is the output for the following?
(c) Numbers (d) Functions
‘mammals’. find (‘ma’,2,4)
 [Ans. (b) Strings]
w

(a) 0 (b) 1 (c) –1 (d) 3


 [Ans. (c) –1] 3. When a string is define(d) Python allocate an
27. What is the output for the following? __________ for its each character.
‘mammals’. find (‘ma’,2,5) (a) Function (b) Arguments value
(a) 0 (b) 3 (c) –1 (d) 1 (c) Index value (d) Parameter
 [Ans. (b) 3]  [Ans. (c) Index value]

105
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. The subscript can be _________ integer 13. The ‘in’ and ‘not in ’ operators are called as
numbers. _____ operators.
Unit II - Chapter 8

(a) Positive (b) Negative (a) string (b) string formatting


(c) Floating (c) membership (d) reference
 [Ans. (c) membership]
(d) Positive or negative
Choose correct pair

m
 [Ans. (d) Positive or negative]
1. (a) % d – unsigned decimal integer.
5. Python provides a function ___________ (b) % 0 – short number in floating point
to change all occurrences of a particular (c) % i – signed decimal integer

co
character in a string. (d) % x – octal integer.
(a) replace( ) (b) change ( )  [Ans. (c) % i – Signed decimal integer]
(c) change all ( ) (d) repalceall () 2. (a) \a – Aarriage Return (b)\b – Backspace
 [Ans. (a) replace( )] (c) \v – Value ooo ( d ) \ f – For m fe e d

s.
 [Ans. (b) \b – Backspace]
6. In Python, the entire string variable removed
using __________ command Choose incorrect pair
(a) Remove (b) Replace 1. (a) % u – unsigned decimal integer

ok
(c) Del (d) Delete (b) % d – signed decimal integer
 [Ans. (c) Del] (c) % e – exponential notation
7. The _______ operator is used to append a new (d) % G – short numbers in exponential
string with an excisting string. notation
o
(a) + (b) + = (c) * = (d) * *
[Ans. (b) + =] [Ans. (b) % d – signed decimal integer]
2. (a) \n – line feed
ab

8. The _______ operator is used to display a


string in multiple number of time. (b) \f – Form feed
(a) * (b)* * (c) + = (d) + + (c) \b – Backspace
 [Ans. (a) *] (d) \h – Horizontal tab
ur

9. ________ is a substring of a mainstring.  [Ans. (d) \h – Horizontal tab]


(a) stride (b) slice 3.
(c) concat (d) append
(a) ‘EARTH’. Lower () earth
[Ans. (b) slice]
.s

(b) ‘Save earth’. Title() Save Earth


10. Write the missing symbol in the following
(c) ‘Save earth ’. Capitalize Save earth
statement.
()
str [start ____ end]
w

(a) ; (b) , (c) : : (d) : (d) ‘Earth ’. Snap case () eARTH


 [Ans. (d) : ]  [Ans. (c) ‘Save earth ’. Capitalize () – Save
11. The formatting operator ________ is used to earth]
w

replacing parts of strings with the data stored Choose the incorrect statement
in variables.
1. (i) String is not a data type in python
(a) # (b) : (c) % (d) : :
(ii) Strings are enclosed with single, double or
w

 [Ans. (c) %] triple quotes.


12. The ________ function is a powerful function (iii) Strings are not immutable.
used for formatting strings. (iv) Strings cannot be changed during execution.
(a) format ( ) (b) string ( ) (a) i and ii (b) i, iii and iv
(c) Slice ( ) (d) format string( ) (c) only iii (d) i and iii
 [Ans. (a) format ( )]  [Ans. (d) i and iii]

106
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. (i) In Python, string are immutable. 5. Write the general format of slice operation.

Strings and String Manipulation


(ii) Python allow to modify the already defined Ans. General format of slice operation:
string. str[start:end]
(iii) Python will not allow deleting a particular Where start is the beginning index and end is
character in string.
the last index value of a character in the string.
(iv) In Python, the index value is only a positive

m
integer. Python takes the end value less than one from
(a) i and iii (b) ii and iv the actual index specified.
(c) i, ii and iv (d) ii and iii 6. What has to be filled in the blank to get the

co
 [Ans. (b) ii and iv] following output
Very Short Answers 2 MARKS (i) Welcome python
(ii) Welcome to learn python
1. How will you manipulate the strings?
From
Ans. (i) Once you define a string, python allocate

s.
an index value for its each character. (a) print ("Welcome" ____ "Python")
(ii) These index values are otherwise called strl = "Welcome"
as subscript which are used to access and (b) print (Strl ____ "to learn python")

ok
manipulate the strings. The subscript can Ans. (a) +
be positive or negative integer numbers.
(b) + =
2. What it means "String in phython are 7. if strl = "Welcome to learn python", then write
immutable"? the output for the following.
Ans. Strings in python are immutable. That means,
o
(i) print (strl [10 : 16])
once you define a string modifications or (ii) print (strl [10 : 16 : 4])
deletion is not allowed.
(iii) print (strl [10 : 16 : 2])
ab

3. Write a python a program to print your name (iv) print (strl [: : 3])
10 times. Ans. (i) Learn
Ans. strl = input ("Enter your name") (ii) r
print (strl * 10) (iii) er
(iv) ceoenyo
ur

4. Write the output for the following if strl =


"THIRIKKURAL" 8. What is the use of formatting operator?
(i) print (strl [0]) Ans. The formatting operator % is used to construct
(ii) print (strl [0:5]) strings, replacing parts of the strings with the
.s

(iii) print (strl [:5]) data stored in variables.


(iv) Print (strl [6:]) 9. Write the output for the following statement.
Ans. (i) T (i) print ("save earth" . title ())
w

(ii) THIRU (ii) print ("Save Earth" . swapcase ())


(iii) THIRU Ans. (i) Save Earth
(iv) KURAL (ii) sAVE eARTH
w

10. Differentiate upper () and is upper ().


Ans. Syntax Description Example
w

isupper( ) Returns True if the string is in >>> str1=’welcome’


uppercase. >>>print (str1.isupper())
False
upper( ) Returns the exact copy of the >>> str1=’welcome’
string with all letters in uppercase. >>>print (str.upper( ))
WELCOME

107
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


11. What is the use of title () function? Give example.
Ans.
Unit II - Chapter 8

Syntax Description Example


title( ) Returns a string in title case >>> str1='education department'
>>> print(str1.title())

m
Education Department

co
Short Answers 3 MARKS 4. Write the formats string characters for the
following
1. How the positive and negative subscript values
(i) Exponential notation
are assigned? Give example.
(ii) Floating point numbers
Ans. The positive subscript 0 is assigned to the first

s.
character and n-1 to the last character, where (iii) Short numbers in exponential notation
n is the number of characters in the string. The Ans. (i) % e or % E
negative index assigned from the last character (ii) % f

ok
to the first character in reverse order begins (iii) % g or % G
with -1.
Example : 5. Write the description for the following escape
sequence.
String S C H O O L
(i) \r
o
Positive 0 1 2 3 4 5
subscript (ii) \000
(iii) \v
ab

Built in –6 –5 –4 –3 –2 –1
functions Ans. (i) carriage return
2. Write the usage of the following format string (ii) character with octal value
characters. (iii) vertical tab
(i) % c
ur

6. Write the output of the following statements.


(ii) % d (or) % i
(i) print (len ("Corporation"))
(iii) % s
Ans. (i) character (ii) print ("school", Capitalize ())
(iii) print ("Welcome" center (15, ‘*’))
.s

(ii) Signed decimal integer


(iii) String Ans. (i) 11
3. Fill in the blanks (ii) School
w

Format Usage (iii) * * * * Welcome * * * *


character 7. Write the output of the following statements.
i) ________ Unsigned decimal integer strl = ‘mammals’
w

ii) % 0 ________
(i) strl. find (‘ma’)
iii) ________ Hexadecimal integer (ii) strl. find (‘ma’, 2)
________
w

iv) % i (iii) strl. find (‘ma’, 2, 4)


Ans. (i) %u (iv) strl. find (‘ma’, 2, 5)
(ii) octal integer Ans. (i) 0
(iii) % c or %x (ii) 3
(iv) signed decimal integer.
(iii) - 1
(iv) 3

108
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


8. Write the output of the following statements. 9. Write the output for the following statement.

Strings and String Manipulation


(i) ‘Python 2. 3’ . isalpha () (i) print ("PYTHON" . lower ())
(ii) print ("PYTHON" . islower ())
(ii) ‘Python Program’ . is alnum ()
(iii) print ("PYTHON" . isupper ())
(iii) ‘Python’ . isupper ()
(iv) print ("PYTHON" . upper ())

m
Ans. (i) False
Ans. (i) python
(ii) False
(ii) false
(iii) False

co
(iii) false
(iv) PYTHON

10. Write a note on

s.
(i) isalnum () (ii) isalpha () (iii) isdigit ()
Ans.
Syntax Description Example

ok
(i) isalnum Returns True if the string contains only >>>str1=’Save Earth’
() letters and digit. It returns False. If the >>>str1.isalnum()
string contains any special character False
like _, @, #, *, etc. The function returns False as space is an
o
alphanumeric character.
>>>’Save1Earth’.isalnum()
True
ab

(ii) isalpha( ) Returns True if the string contains only >>>’Click123’.isalpha()


letters. Otherwise return False. False
>>>’python’.isalpha( )
True
ur

(iii) isdigit( ) Returns True if the string contains only >>> str1=’Save Earth’
numbers. Otherwise it returns False. >>>print(str1.isdigit( ))
False
.s

11. Write the out put for the following statement.


strl = "Raja Raja Chozhan"
w

(i) print (strl . count (‘Raja’))


(ii) print (strl . count (‘R’))
(iii) print (strl . count (‘A’))
w

(iv) print (strl . count (‘a’))


(v) print (strl . count (‘a’, 0, 5))
(vi) print (strl . count (‘a’, 11))
w

Ans. (i) 2 (ii) 2


(iii) 0 (iv) 5
(v) 2 (vi) 1

109
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Long Answers 5 MARKS 4. Write a python program that accept a string
from the user and display the same after
Unit II - Chapter 8

1. Write a python program to print the following removing vowels from it.
pattern Ans. def rem_vowels(s):
* temp_str=''
for i in s:

m
**
if i in "aAeEiIoOuU":
*** pass
**** else:

co
***** temp_str+=i
print ("The string without vowels: ", temp_str)
Ans. str1=' * '
str1= input ("Enter a String: ")
i=1 rem_vowels (str1)
while i<=5: 5. Write a python program that searches and

s.
print (str1*i) counts the occurrences of a character in string.
i+=1 Ans. def count(s, c):
c1=0

ok
2. Write a python program to display the number for i in s:
of vowels and consonants in the given string. if i == c:
Ans. str1=input ("Enter a string: ") c1+=1
str2="aAeEiIoOuU" return c1
str1=input ("Enter a String: ")
o
v,c=0,0
ch=input ("Enter a character to be searched: ")
for i in str1: cnt=count (str1, ch)
ab

if i in str2: print ("The given character {} is occurs {} times


v+=1  in the given string".format(ch,cnt))
Output:
else:
Enter a String: Software Engineering
c+=1 Enter a character to be searched: e
ur

print ("The given string contains { } vowels and The given character e is occurs 3 times in the
 { } consonants".format(v,c)) given string
6. Write the program to display the following
3. Write a python program to create an
.s

pattern
Abecedarian series, (Abecedarian refers list of
*****
elements appear in alphabetical order).
****
Ans. str1="ABCDEFGH"
w

***
str2="ate" **
for i in str1: *
Ans. strl = ‘*’
w

print ((i+str2),end='\t')
i=5
Output :
while (i > = 1)
Aate Bate Cate Date Eate Fate Gate Hate print (strl * i)
w

i=1


110
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

-

UNIT III MODULARITY AND OOPS
 

LISTS, TUPLES, SETS

m
Chapter

9 AND DICTIONARY

co
CHAPTER SNAPSHOT

s.
9.1 Introduction to List
9.1.1. Create a List in Python

ok
9.1.2. Accessing List elements
9.1.3. List Length
9.1.4. Accessing elements using for loop
9.1.5. Changing list elements
9.1.6. Adding more elements in a list
o
9.1.7. Inserting elements in a list
9.1.8. Deleting elements from a list
ab

9.1.9. List and range ( ) function


9.1.10. List comprehensions
9.1.11. Other important list function
9.1.12. Programs using List
9.2 Tuples
ur

9.2.1. Advantages of Tuples over list


9.2.2. Creating Tuples
9.2.3. Accessing values in a Tuple
9.2.4. Update and Delete Tuple
.s

9.2.5. Tuple Assignment


9.2.6. Returning multiple values in Tuples
9.2.7. Nested Tuples
w

9.2.8. Programs using Tuples


9.3 Sets
9.3.1. Creating a Set
9.3.2. Creating Set using List or Tuple
w

9.3.3. Set Operations


9.3.4. Programs using Sets
9.4 Dictionaries
w

9.4.1. Creating a Dictionary


9.4.2. Dictionary Comprehensions
9.4.3. Accessing, Adding, Modifying and Deleting elements from a Dictionary
9.4.4. Difference between List and Dictionary

[111]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science

Evaluation 9. Which of the following statement is not


Unit III - Chapter 9

correct? [HY-2019]
(a) A list is mutable
Part - I (b) A tuple is immutable
Choose the best answer  (1 mark) (c) The append() function is used to add an

m
1. Pick odd one in connection with collection element
data type (d) The extend() function is used in tuple to add
(a) List (b) Tuple elements in a list
(c) Dictionary (d) Loop  [Ans. (d) The extend() function is used in

co
 [Ans. (d) Loop]  tuple to add elements in a list]
2. Let list1=[2,4,6,8,10], then print(List1[-2]) 10. Let setA={3,6,9}, setB={1,3,9}. What will be
will result in
the result of the following snippet? [PTA-2]
(a) 10 (b) 8 (c) 4 (d) 6
print(setA|setB)
 [Ans. (b) 8]

s.
3. Which of the following function is used to (a) {3,6,9,1,3,9} (b) {3,9}
count the number of elements in a list? (c) {1} (d) {1,3,6,9}
(a) count() (b) find()  [Ans. (d) {1,3,6,9}]

ok
(c) len() (d) index() 11. Which of the following set operation includes
 [Ans. (c) len()] all the elements that are in two sets but not the
4. If List=[10,20,30,40,50] then List[2]=35 will one that are common to two sets?
result  [Govt. MQP-2019]
(a) [35,10,20,30,40,50] (a) Symmetric difference (b) Difference
o
(b) [10,20,30,40,50,35] (c) Intersection (d) Union
(c) [10,20,35,40,50] (d) [10,35,30,40,50]
 [Ans. (a) Symmetric difference]
ab

 [Ans. (c) [10,20,35,40,50]]


5. If List=[17,23,41,10] then List.append(32) will 12. The keys in Python, dictionary is specified by
result [PTA-1] (a) = (b) ; (c) + (d) :
(a) [32,17,23,41,10] (b) [17,23,41,10,32]  [Ans. (d) :]
(c) [10,17,23,32,41] (d) [41,32,23,17,10] Part - II
ur

 [Ans. (b) [17,23,41,10,32]] Answer the following questions


6. Which of the following Python function can
be used to add more than one element within  (2 marks)
an existing list? 1. What is List in Python?
.s

(a) append() (b) append_more() Ans. (i) A list in Python is known as a “sequence
(c) extend() (d) more() data type” like strings. It is an ordered
 [Ans. (c) extend()] collection of values enclosed within square
w

7. What will be the result of the following Python brackets [].


code? (ii) Each value of a list is called as element.
S=[x**2 for x in range(5)] It can be of any type such as numbers,
w

print(S) characters, strings and even the nested lists


(a) [0,1,2,4,5] (b) [0,1,4,9,16] as well.
(c) [0,1,4,9,16,25] (d) [1,4,9,16,25]
2. How will you access the list elements in reverse
 [Ans. (b) [0,1,4,9,16]]
w

order? [QY-2019; HY-2019]


8. What is the use of type() function in python?
(a) To create a Tuple Ans. Python enables reverse or negative indexing
(b) To know the type of an element in tuple for the list elements. Thus, python lists index in
(c) To know the data type of python object opposite order. The python sets -1 as the index
(d) To create a list. value for the last element in list and -2 for the
 [Ans. (c) To know the data type of python preceding element and so on. This is called as
object] Reverse Indexing.

112
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. What will be the value of x in following python 2. Write a short note about sort( ).
code? Ans. Sort ( ) :

Lists, Tuples, Sets and Dictionary


List1=[2,4,6[1,3,5]] (i)  It sorts the element in list.
x=len(List1) (ii)  sort ( ) will affect the original list.
Ans. x = 4. Syntax :

m
4. Differentiate del with remove( ) function of List.sort(reverse=True|False, key=myFunc)
List. Sorts the element in list :
Ans. Both arguments are optional
del function remove ( ) function (i)  If reverse is set as True, list sorting is in

co
descending order.
(i) del statement is remove( ) function
is used to delete (ii)  Ascending is default.
used to delete
elements of a list if its (iii) Key=myFunc; “myFunc” - the name of the
known elements
index is unknown. user defined function that specifies the

s.
(ii) The del state- The remove () func- sorting criteria.
ment can also tion can be used to (iv) sort( ) will affect the original list.
be used to delete delete one or more Example :
elements if the index MyList=['Thilothamma', 'Tharani', 'Anitha',
entire list.

ok
value is not known.  'SaiSree', 'Lavanya']
5. Write the syntax of creating a Tuple with n MyList.sort( )
number of elements. print(MyList)
Ans. Syntax: Output:
o
Tuple_Name = (E1, E2, E2 ....... En) #Tuple with ['Anitha', 'Lavanya', 'SaiSree', 'Tharani',
 n number elements 'Thilothamma']
ab

Tuple_Name = E1, E2, E3 ..... En # Elements of a 3. What will be the output of the following code?
 tuple without parenthesis list = [2**x for x in range(5)]
6. What is Set in Python?  [PTA-4; QY-2019] print(list)
Ans. (i) In Python, a Set is another type of Ans. Output : [1, 2, 4, 8, 16]
collection data type. A Set is a mutable
ur

and an unordered collection of elements 4. Explain the difference between del and clear( )
without duplicates. in dictionary with an example.
(ii) That means the elements within a set cannot Ans.
be repeated. This feature used to include
.s

del clear( )
membership testing and eliminating (i) Th e del The fuction clear ( )
duplicate elements.
statements is used is used to delete all
Part - III to delete known the elements in list
w

Answer the following questions elements


(ii) The del statement It deletes only the
 (3 marks) can also be used elements and retains
w

1. What are the advantages of Tuples over a list? to delete entire the list.
Ans. (i) The elements of a list are changeable list.
(mutable) whereas the elements of a tuple
w

5. List out the set operations supported by


are unchangeable (immutable), this is the
python.
key difference between tuples and list.
Ans. Set Operations :
(ii)  The elements of a list are enclosed within
square brackets. But, the elements of a (i) Union : It includes all elements from two
tuple are enclosed by parenthesis. or more sets.
(iii) Iterating tuples is faster than list. (ii) Intersection : It includes the common
elements in two sets.
113
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iii) Difference : It includes all elelments that Example :
are in first set (say set A) but not in the
Unit III - Chapter 9

>>> MyList=[34,98,47,'Kannan',
second set (say set B).  'Gowrisankar', 'Lenin', 'Sreenivasan' ]
(iv) Symmetric difference : It includes all the >>> MyList.insert(3, 'Ramakrishnan')
elements that are in two sets (say sets A and
B) but not the one that are common to two >>> print(MyList)

m
sets. Output : [34, 98, 47, 'Ramakrishnan', 'Kannan',
 'Gowrisankar', 'Lenin', 'Sreenivasan']
6. What are the difference between List and (i) In the above example, insert( ) function
Dictionary? [PTA-3; HY-2019] inserts a new element 'Ramakrishnan' at

co
Ans. the index value 3, ie. at the 4th position.
List Dictionary (ii) While inserting a new element, the existing
(i) A list is an A dictionary is a elements shifts one position to the right.
ordered mixed collection of Adding more elements in a list using append():

s.
collection elements and it stores (i) The append( ) function is used to add a
of values or a key along with its single element in a list.
elements of any element. (ii) But, it includes elements at the end of a list.

ok
type. Syntax :
(ii) It is enclosed The key value pairs are List.append (element to be added)
within square enclosed with curly Example :
brackets [ ] braces { } >>> Mylist=[34, 45, 48]
(iii) Syntax : Syntax or defining a
o
>>> Mylist.append(90)
Variable = dictionary : >>> print(Mylist)
[element-1, Dictionary_Name
Output : [34, 45, 48, 90]
ab

element-2, = {Key_1: Value_1,


element-3 ....... Key_2:Value_2, Adding more elements in a list using extend():
element-n] ............. (i) The extend( ) function is used to add more
Key_n: Value_n than one element to an existing list.
} (ii) In extend( ) function, multiple elements
ur

(iv) The commas The keys in a Python should be specified within square bracket
work as a dictionary is separated as arguments of the function.
separator for by a colon (:) while Syntax : List.extend ( [elements to be added])
the elements. the commas work as a Example :
.s

separator for the ele- >>> Mylist=[34, 45, 48]


ments. >>> Mylist.extend([71, 32, 29])
>>> print(Mylist)
Part - IV
w

Output : [34, 45, 48, 90, 71, 32, 29]


Answer the following questions
2. What is the purpose of range( )? Explain with
 (5 marks)
w

an example. [HY-2019]
1. What the different ways to insert an element in Ans. The range( ) is a function used to generate a series
a list. Explain with suitable example. of values in Python. Using range( ) function, you
Ans. Inserting elements in a list using insert(): can create list with series of values. The range( )
w

(i) The insert ( ) function helps you to include function has three arguments.
an element at your desired position. Syntax of range ( ) function:
(ii) The insert( ) function is used to insert an range (start value, end value, step value)
element at any position of a list. where,
Syntax : (i) start value – beginning value of series.
Zero is the default beginning value.
List.insert (position index, element)

114
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(ii) end value – upper limit of series. Python 3. What is nested tuple? Explain with an example.
takes the ending value as upper limit – 1.

Lists, Tuples, Sets and Dictionary


Ans. Nested Tuples :
(iii) step value – It is an optional argument,
(i) In Python, a tuple can be defined inside
which is used to generate different interval
another tuple; called Nested tuple. In a
of values.
nested tuple, each tuple is considered as
Example: Generating whole numbers upto 10

m
an element. The for loop will be useful to
for x in range (1, 11): access all the elements in a nested tuple.
print(x)
(ii) Example :
Output :
Toppers = (("Vinodini", "XII-F", 98.7), 

co
1
 ("Soundarya", "XII-H", 97.5),
2
3 ("Tharani", "XII-F", 95.3), ("Saisri",
 "XII-G", 93.8))
4
5 for i in Toppers:

s.
6 print(i)
7 (iii) Output :
8 ('Vinodini', 'XII-F', 98.7)

ok
9 ('Soundarya', 'XII-H', 97.5)
10 ('Tharani', 'XII-F', 95.3)
Creating a list with series of values : ('Saisri', 'XII-G', 93.8)
(i) Using the range( ) function, a list can be
4. Explain the different set operations supported
o
created with series of values. To convert
the result of range( ) function into list, one by python with suitable example.
more function called list is needed( ). The  [PTA-1; QY-2019]
ab

list( ). function makes the result of range( ) Ans. A set is a mutable and an unordered collection of
as a list.
elements without duplicates.
(ii) Syntax: List_Varibale = list ( range ( ) ) Set operations: The set operation such as
(iii) Example : Union, Intersection, difference and symmetric
difference.
ur

>>> Even_List = list(range(2,11,2))


>>> print(Even_List) Union: It includes all elements from two or
Output : [2, 4, 6, 8, 10] more sets [Govt. MQP-2019; PTA-2]
(iv) In the above code, list( ) function takes the Set A Set B
.s

result of range( ) as Even_List elements.


Thus, Even_List list has the elements of first
five even numbers.
w

Similarly, we can create any series of values


using range( ) function. The following
example explains how to create a list with (i) In python, the operator | is used to union of
w

squares of first 10 natural numbers. two sets. The function union( ) is also used
Example : Generating squares of first 10 to join two sets in python.
natural numbers (ii) Example : Program to Join (Union) two
squares = [ ] sets using union operator
w

for x in range(1,11): set_A={2,4,6,8}


s = x ** 2 set_B={'A', 'B', 'C', 'D'}
squares.append(s) U_set=set_A|set_B
print (squares) print(U_set)
Output : [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Output :
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
115
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Intersection :  [Govt. MQP-2019; PTA-2]
Unit III - Chapter 9

(i) It includes the common elements in two Set A Set B


sets

Set A Set B

m

(ii) The caret (^) operator is used to symmetric

co
difference set operation in python. The
(ii) The operator & is used to intersect two sets function symmetric_difference( ) is also
in python. The function intersection( ) is
used to do the same operation.
also used to intersect two sets in python.
(iii) Example : Program to symmetric

s.
(iii) Example : Program to insect two sets using
intersection operator difference of two sets using caret operator
set_A={'A', 2, 4, 'D'} set_A={'A', 2, 4, 'D'}

ok
set_B={'A', 'B', 'C', 'D'} set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B) print(set_A ^ set_B)
Output : Output :
{'A', 'D'}
{2, 4, 'B', 'C'}
Difference :
o
(i) It includes all elements that are in first set Hands on Experience
(say set A) but not in the second set (say set B)
ab

1. Write a program to remove duplicates from a


Set A Set B list.
Ans. Method I :
mylist = [2,4,6,8,8,4,10]
ur

myset = set(mylist)
print(mylist)
Output : {2, 4, 6, 8, 10}
.s

(ii) The minus (–) operator is used to difference Method II :


set operation in python. The function def remove(duplicate):
difference( ) is also used to difference final_list=[]
operation.
w

for num in duplicate:


(iii) Example : Program to difference of two if num not in final_list:
sets using minus operator final_list.append(mum)
w

set_A={'A', 2, 4, 'D'} return final_list


set_B={'A', 'B', 'C', 'D'} duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(set_A - set_B) print(remove(duplicate))
w

Output : [2, 4, 10, 20, 5]


Output : {2, 4}
Symmetric difference : 2. Write a program that prints the maximum
value in a Tuple.
(i) It includes all the elements that are in two Ans. tuple = (456, 700, 200)
sets (say sets A and B) but not the one that print (“max value : ”, max (tuple ))
are common to two sets. Output : max value : 700

116
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Write a program that finds the sum of all the 7. Write a program that creates a list of numbers
numbers in a Tuples using while loop. from 1 to 50 that are either divisible by 3 or

Lists, Tuples, Sets and Dictionary


Ans. tuple = (1, 5, 12) divisible by 6.
s=0 Ans. n = [ ]
s = []
i=0 for x in range(1,51):

m
while(i < len (tuple): n.append(x)
s = s + tuple [i] for x in range(1, 51):
i+=1 if(x%3 == 0) or (x%6 ==0):
print ("Sum of elements in tuple is ", s) s.append(x)

co
Output : Sum of elements in tuple is 18. print ("The numbers divisible by 3 or 6 is ", s)
Output :
4. Write a program that finds sum of all even The numbers divisible by 3 or 6 is
numbers in a list. [3, 6, 9, 5, 12, 15, 18, 21, 24, 27, 30, 33, 36,
Ans. numlist = []  39, 42, 45, 48]

s.
even_sum = 0 8. Write a program to create a list of numbers in
number = int(input("Please enter the total no. of the range 1 to 20. Then delete all the numbers
 list elements")) from the list that are divisible by 3.

ok
Ans. num = [ ]
for i in range(1, number + 1)
for x in range (1,21):
value = int(input("Please enter the value")) num.append(x)
numlist.append(value) print ("The list of numbers from 1 to 20 =", num)
for j in range(number): for index, i in enumerate(num):
o
if(numlist[j] %2 ==0): if(i % 3 == 0)
even_sum = even_sum + numlist[j] del num[index]
print (“Sum of even no. in this list = ", even_sum) print("The list after deleting numbers", num)
ab

Output :
Output :
The list of numbers from 1 to 20 = [1,2,3,4 ... 20]
Please enter the total no of list elements : 5 The list after deleting numbers [1, 2, 4, 5, 7, 8, 10,
Please enter the value : 10  11, 13, 14, 16, 17, 19, 20]
Please enter the value : 11 9. Write a program that counts the number of
ur

Please enter the value : 12 times a value appears in the list. Use a loop to
Please enter the value : 13 do the same.
Please enter the value : 14 Ans. a = []
The sum of even no. in this list = 60 n = int(input"Enter number of elements :"))
.s

5. Write a program that reverse a list using a for i in range(1, n+1)


loop. b = int(input("Enter element"))
a.append(b)
Ans. def reverse (list):
k=0
w

list.reverse() num = int(input("Enter the number to be


return list  counted :"))
list = [10, 11, 12, 13, 14, 15] for j in a :
w

print (reverse (list) if (j ==num):


Output : k = k +1
15, 14, 13, 12, 11, 10 print("Number of times", num, "appears is", k)
Output :
w

6. Write a program to insert a value in a list at the Enter number of elements : 4


specified location. Enter element : 23
Ans. vowel = ['a', 'e', 'i', 'u'] Enter element : 45
vowel. insert(3, 'o') Enter element : 23
print ('updated list', vowel) Enter element : 67
Output : Enter the number to be counted : 23
updated list ['a', 'e', 'i', 'o', 'u'] Number of times 23 appears is 2

117
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. Write a program that prints the maximum and 4. What are the collection data types available in
minimum value in a dictionary. Python?
Unit III - Chapter 9

[PTA-6]
Ans. my_dict = {'x' : 500, 'y' : 5874, 'z' : 560} Ans. Python programming language has four
val = my_dict . values () collections of data types such as List, Tuples, Set
print ('max value', max (val)) and Dictionary.
print (“min value', min (val))
3 MARKS

m
Output :
max value 5874 1. Write execution table for the following Python
min value 500 code. [PTA-1]
Marks=[10, 20, 30, 40, 50]
Questions and Answers

co
PTA i=0
sum = 0
1 MARK while i < 4:
1. Which function is used to find length of a list sum+=Marks[i]
in Python? [PTA-3] i+=1

s.
(a) for() (b) range() Ans.
(c) len() (d) length
 [Ans. (c) len ()] print
Iteration i while i<4 i = i+1
2. Which Functrion is used to generate a series of (Marks[i])

ok
values in Python? [PTA-4] 1. 0 0<4 True Marks [0] = 10 0+1 =1
(a) series() (b) range()
(c) list() (d) tuple() 2. 1 1<4 True Marks [1] = 20 1+1 =2
 [Ans. (b) range()] 3. 2 2<4 True Marks [2] = 30 2+1 =3
3. Which is a mutable and unordered collection
o
4. 3 3<4 True Marks [3] = 40 3+1 =4
of elements without duplicates? [PTA-5]
(a) List (b) Tuple 5. 4 4<4 False Marks [4] = 50 4+1 =5
ab

(c) Set (d) Dictionary 2. Write a simple python program with list of five
 [Ans. (c) Set]
marks and print the sum of all the marks using
4. How many elements are in the list given below?
 [PTA-6] while loop. [PTA-5]
MyList=[78, 91, 34, [32, 61, 85], 65] Ans. marks=[]
subjects=['Tamil', 'English', 'Physics',
ur

(a) 3 (b) 4 (c) 5 (d) 7


 [Ans. (d) 7]  'Chemistry', 'Comp. Science']
2 MARKS for i in range(5):
m=int(input("Enter Mark = "))
1. Write the syntax of creating dictionary in marks.append(m)
.s

Python. [PTA-1]
for j in range(len(marks)):
Ans. Syntax
print("{ }. { } Mark = { }
Dict = { expression for variable in sequence [if
".format(j1+,subjects[j],marks[j]))
w

condition]}
print("Total Marks = ", sum(marks))
2. What will be the output of the following Output :
snippet? [PTA-2]
Enter Mark = 45
Mydict={chr(x):x for x in range(97, 102)}
w

Enter Mark = 98
print(Mydict)
Enter Mark = 76
Ans. Output :
{97:98, 98:99, 99:100, 100:101, 101:102} Enter Mark = 28
w

Enter Mark = 46
3. What will be the output of the following
snippet? [PTA-3] 1. Tamil Mark = 45
set_A = {'A', 2, 4 'D'} 2. English Mark = 98
set_B = {'A', 'B', 'C', 'D'} 3. Physics Mark = 76
print(set_A & set_B) 4. Chemistry Mark = 28
Ans. Output : 5. Comp. Science Mark = 46
{'A', 'D'} Total Marks = 293

118
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. What is dictionary? [PTA-3] (iv) Here, the while loop is used to read all the
Ans. (i) In Python, a dictionary is a mixed collection elements. The initial value of the loop is

Lists, Tuples, Sets and Dictionary


of elements. Unlike other collection data zero, and the test condition is i < 4, as long as
types such as a list or tuple, the dictionary the test condition is true, the loop executes
type stores a key along with its element. and prints the corresponding output.
(ii) The keys in a Python dictionary is separated (v) During the first iteration, the value of i is

m
by a colon ( : ) while the commas work as zero, where the condition is true. Now, the
a separator for the elements. The key value following statement print (Marks [i]) gets
pairs are enclosed with curly braces { }. executed and prints the value of Marks [0]

co
element ie. 10.
5 MARKS
(vi) The next statement i = i + 1 increments
1. What will be the output of the following the value of i from 0 to 1. Now, the flow
Python program?  [PTA-4] of control shifts to the while statement for
N = [] checking the test condition. The process

s.
for x in range(1, 11): repeats to print the remaining elements of
N.append(x) Marks list until the test condition of while
Num=tuple(N) loop becomes false.

ok
print(Num) The following table shows that the execution of
for index, i in enumerate(N): loop and the value to be print.
if(i%2==1): Itera while print
del N[index] i i=i+1
tion i<4 (Marks[i])
print(N)
o
1 0 0 < 4 True Marks [0] 0+1=1
Ans. Output :
The list of numbers from 1 to 10 = [1, 2, 3, 4, 5, = 10
ab

 6, 7, 8, 9, 10] 2 1 1 < 4 True Marks [1] 1+1=2


The list after deleting even numbers = [1, 3, 5, 7, = 23
9] 3 2 2 < 4 True Marks [2] 2+1=3
2. How would you access elements of a list? = 41
ur

 [PTA-6] 4 3 3 < 4 True Marks [3] 3+1=4


Ans. (i) Loops are used to access all elements from
= 75
a list. The initial value of the loop must be
zero. Zero is the beginning index value of a 5 4 4 < 4 False -- --
.s

list.
(ii) Example : Government Exam Questions and Answers
Marks = [10, 23, 41, 75]
i=0 1 MARK
w

while i < 4: 1. Which command deletes the elements and it


print (Marks[i]) retains list. [QY-2019]
i=i+1 (a) remove()
w

Output : (b) del()


10 (c) Clear()
23
(d) Pop()[Ans. (c) Clear()]
w

41
75 2. ___ is the mixed collection of elements.
(iii) In the above example, Marks list contains (a) Lists [QY-2019]
four integer elements i.e., 10, 23, 41, 75. (b) Sets
Each element has an index value from 0. (c) Dictionary
The index value of the elements are 0, 1, 2, (d) Tuples [Ans. (c) Dictionary]
3 respectively.

119
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2 MARKS iii) Mylist.extend ([110, 120, 130])
Unit III - Chapter 9

print (Mylist)
1. What will be the output of the following
iv) del Mysubjects[3:7]
snippet? [Govt. MQP-2019]
v) del (Mylist)
alpha=list(range(65, 70))
for x in alpha: additional questions and Answers

m
print(chr(x), end='\t')
Ans. Output : Choose the Correct Answer 1 MARK
65 1. How many collection of datatypes in python?

co
66 (a)
3 (b) 4 (c) 2 (d) 5
67  [Ans. (b) 4]
68
69 2. Which of the following is not datatype in
Python?
70

s.
(a) List (b) Tuples
5 MARKS (c) String (d) Set
1. Compare remove(), pop() and clear() function  [Ans. (c) String]

ok
in Python. [Govt. MQP-2019] 3. Which of the following is an ordered collection
Ans.
of values?
(a) Set (b) Tuples
remove() pop() clear() (c) List (d) Dictionary
1. remove() pop() function The function  [Ans. (c) List]
o
function is deletes and clear() is 4. Which of the following datatype enclosed with
used to delete returns the used to
[ ]?
elements of a last element delete all the
ab

elements in (a) Tuples (b) List


list if its index of a list if the (c) Dictionary (d) Set
is unknown. index is not list, it deletes
only the  [Ans. (b) List]
given. elements and 5. In list, the negative index number begin with
retains the
(a) 0 (b) 1 (c) – 1 (d) 0.1
ur

list.
 [Ans. (c) –1]
2. Removes Removes Removes
element from an arbitrary all elements 6. a = [‘A’, 2, 3, [4, 5, 6]] is an example of
the set. element. from a set. (a) Tuple (b) Set
.s

(c) List (d) Dictionary


2. Mylist = [10, 20, 30, 49, 50, 60, 70, 80, 90, 100]  [Ans. (c) List]
Write the Python commands for the following
7. Which of the following can be used to access
based on above list. [HY-2019]
w

an element in a list?
i) To print all elements in list.
(a) Subscript (b) Function
ii) Find list length.
(c) Integer (d) Identifier
iii) Add multiple elements [110, 120, 130]
 [Ans. (a) Subscript]
w

iv) Delete from fourth element to seventh


element. 8. In li = [10, 23, 41, 75], the negative index value
v) Delete entire list. of 41 is
(a) 2 (b) – 1 (c) – 2 (d) – 3
w

Ans. i) Mylist.[10, 20, 30, 40, 50, 60, 70, 80, 90,
 [Ans. (c) –2]
100]
for x in mylist: 9. If python sets – 1 as the index value for the last
element is called
print (x)
(a) Oppositive indexing (b) Tuple indexing
ii) Mylist = [10, 20, 30, 40, 50, 60, 70, 80, 90,
(c) Reverse index (d) List indexing
100]
 [Ans. (c) Reverse index]
len (Mylist)
120
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. How many times the following loop executes? 19. How many ways to delete and element from a
li = [10, 23, 41, 75] list?

Lists, Tuples, Sets and Dictionary


i=0 (a) 2 (b) 3
while i > = – 4: (c) 4 (d) None of these
print (li [i])  [Ans. (a) 2]
i+=1 20. Which of the following statement is used to

m
(a) – 4 (b) 4 delete an element from the list?
(c) 0 (d) Error (a) Remove (b) Del
 [Ans. (d) Error] (c) Delete (d) Case
 [Ans. (b) Del]

co
11. Which function is used to set the upper limit
21. Which of the following is used to delete known
in a loop to read all elements of a list?
elements where the index value is known?
(a) upper () (b) limit
(a) del (b) delete
(c) len () (d) loop () (c) remove () (d) del ()
 [Ans. (c) len ()]  [Ans. (c) remove ()]

s.
12. What is the output from the following? 22. Which of the following function is used to
li = [‘T’, ‘E’, ‘C’, ‘M’] delete one or more elements in the list where
for i in li: the index value is not known
print (li [1]) (a) del () (b) remove ()

ok
(a) T (b) E (c) C (d) M (c) delete () (d) delmore ()
 [Ans. (b) E]  [Ans. (b) remove ()]
13. Which of the following operator can be used 23. Which of the following command deletes only
to alter the range of elements in the list? the elements in the list?
(a) del () (b) pop ()
o
(a) = = (b) : (c) : : (d) =
 [Ans. (d) =] (c) clear () (d) remove ()
14. Which function is used to add a single element  [Ans. (c) clear ()]
ab

to an existing list? 24. Which of the following function is used to


(a) add () (b) extend () delete only are element from a list?
(c) append () (d) addlist () (a) pop () (b) del
 [Ans. (c) append ()] (c) delete () (d) clear ()
15. Which of the following function is used to add  [Ans. (a) pop ()]
ur

more than one element in an existing list? 25. How many argument used in the range
(a) append () (b) extend () function?
(c) more () (d) addmore () (a) 3 (b) 4
 [Ans. (b) extend ()] (c) 2 (d) Only one
.s

 [Ans. (a) 3]
16. Predict the output for the following.
26. Which function is used to convert the result of
mylist = [34, 45, 48] range () function in to list?
print(mylist. append (90)) (a) convert () (b) range ()
w

(a) 34, 45, 48, 90 (b) 90, 34, 45, 48 (c) list () (d) listrange ()
(c) 34, 45, 90, 48 (d) 34, 45, 90, 48  [Ans. (c) list ()]
 [Ans. (a) 34, 45, 48, 90] 27. What is the output for the following?
17. Which of the following function used to
w

li = list (range (2, 5, 2))


include multiple element in the list? print (li)
(a) append () (b) extend () (a) [2, 4] (b) [2, 3, 4]
(c) insert () (d) endlist () (c) [2, 3, 4, 5] (d) [2, 3, 4]
w

 [Ans. (b) extend ()]  [Ans. (a) [2, 4]


18. Which of the following function used to 28. What is the output for the following?
include an element in a list at a desired s = [i * * 2 for x in range (1, 2)]
position? print (s)
(a) append () (b) extend () (a) [1, 4] (b) [1, 2]
(c) insert () (d) format () (c) [1] (d) (1, 4)
 [Ans. (c) insert ()] (e) (1)  [Ans. (c) [1]]

121
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


29. Which of the following is a simplest way of 38. What is the output for the following?
creating sequence of elements that satisfy (a, b) = (34)
Unit III - Chapter 9

certain condition? (a) a = 34 (b) b = 34


(a) Tuple comprehension (b) Dictionary (c) a = 34, b = 34 (d) Error
(c) Set comprehension  [Ans. (d) Error]
(d) List comprehension
39. Which of the following is an unordered

m
 [Ans. (d) List comprehension] collection of elements without duplicates?
30. Which of the following function returns the (a) List (b) Tuple
number of similar elements present in the list? (c) Set (d) All of these

co
(a) element () (b) count ()  [Ans. (c) Set]
(c) return () (d) find ()
40. A set is created using
 [Ans. (b) count ()]
(a) [ ] (b) { }
31. If reverse is set as True, list sorting is in (c) ( ) (d) { ( ) }
(a) ascending order (b) descending order

s.
 [Ans. (b) { }]
(c) no sorting (d) multiple sorting
 [Ans. (c) no sorting] 41. What is the output for the following?
a = {1, 2, 2, 3}
32. Using sort (), the default sorting is print (a)

ok
(a) ascending (b) descending (a) {1, 2} (b) {1, 2, 2, 3}
(c) no sorting (d) criteria sorting (c) {1, 2, 3} (d) {1, 2, 3}
 [Ans. (a) ascending]  [Ans. (d) {1, 2, 3}]
33. Which of the following argument is optional 42. Which of the following operator is used to join
o
in sort ()? two sets in python?
(a) Reverse (b) Key (a) & (b) ^ (c) | (d) %
ab

(c) True / false (d) a and b  [Ans. (c) |]


 [Ans. (d) a and b]
43. A = B | C is equivalent to
34. What is the output for the following? (a) A = B. set (c) (b) A = B. join (c)
li = [36, 12, 12] (c) A = B. union (c) (d) A.B. Set (c)
x = mylist. index (12)  [Ans. (c) A = B. union (c)]
ur

print (x)
(a) 0 (b) 1 (c) 2 (d) 1.5 44. Which of the following operator is used to
intersect two sets in python?
 [Ans. (b) 1]
(a) | (b) ^ (c) & (d) $
.s

35. Which of the following can be defined with or  [Ans. (c) &]
without ()?
(a) list (b) set 45. B = A & C is equivalent to
(c) dictionary (d) n o n e o f t h e s e (a) B = A. union (c)
w

 [Ans. (d) none of these] (b) B = A. intersection (c)


(c) B = A. intersect (c)
36. While creating a tuple from a list, the element (d) B = A. interest (c)
should be enclosed with in  [Ans. (b) B = A. intersection (c)]
w

(a) [ ] (b) ( ) (c) { } (d) [( )]


 [Ans. (a) [ ]] 46. Write the output for the following
A = {1, 2, 4, 5}
37. Write the output for the following. B = {1, 6, 7, 5}
w

Tu = {1, 2, 4, 4, 5, 6} print (A + B)
print (Tu (4:)) (a) {1, 2, 4, 5, 6, 7} (b) [2, 4]
(a) 4, 5, 6 (b) 6 (c) {2, 4} (d) (2, 4)
(c) 5, 6 (d) 4, 4, 5, 6  [Ans. (c) {2, 4}]
 [Ans. (c) 5, 6]

122
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


47. Write the output for the following. 6. A list element can be changed using _____
A = {‘A’, 2, 4, ‘D’} operator.

Lists, Tuples, Sets and Dictionary


B = {‘A’, ‘B’, ‘C’, ‘D’} (a) Arithmetic (b) Conditional
print (B - A) (c) Binary (d) Assignment
(a) {‘B’, ‘C’} (b) {2, 4}  [Ans. (d) Assignment]
(c) (2, 4) (d (‘B’, ‘C’)

m
7. Using append () function, and additional
 [Ans. (a) {‘B’, ‘C’}]
value is included with the existing list as ____
48. Which of the following is enclosed with {}? element.
(a) List (b) Tuple (a) first (b) second

co
(c) Key value pairs (d) Dictionary (c) middle (d) last
 [Ans. (c) Key value pairs]
 [Ans. (d) last]
49. Which of the following can be used to access a
particular element in a dictionary? 8. Fill up the blank. dellist [index from _____
(a) { } (b) [ ] (c) ( ) (d) < > index to]

s.
[Ans. (b) [ ] (a) : (b) . (c) : : (d) ;
 [Ans. (a) :]
Match the following
9. The ____ function deletes and returns the last
1. i) ^ 1) Intersection

ok
element of a list if the index is not given?
ii) | 2) Difference (a) del () (b) remove ()
iii) & 3) Union (c) pop () (d) push ()
iv) – 4) Symmetric difference  [Ans. (c) pop ()]
(a) 1, 2, 4, 3, (b) 4, 3, 1, 2
o
10. Tuples are enclosed with _________
(c) 3, 4, 1, 2 (d) 4, 3, 2, 1 (a) [ ] (b) { } (c) ( ) (d) < >
 [Ans. (b) 4, 3, 1, 2]  [Ans. (a) [ ]]
ab

Choose and fill in the blanks


11. ______ represents an abstraction of the
1. A _____ in Python is known as a “sequence sequence of numbers
datatype” (a) Dictionary (b) List
(a) List (b) Set (c) Set (d) Tuple
ur

(c) Dictionary (d) Tuples


 [Ans. (d) Tuple]
 [Ans. (a) List]
12. Iterating ____ is faster than list.
2. A list is enclosed with ________
(a) List (b) Set
(a) { } (b) ( ) (c) < > (d) [ ]
.s

 [Ans. (d) [ ]] (c) Tuples (d) Dictionary ()


 [Ans. (c) Tuples]
3. In list, the positive index number always begin
with ________ 13. While creating a tuple with a single element, add
w

(a) Zero (b) One a ______ at the end of the element.


(c) – 1 (d) 0.0 (a) : (b) . (c) , (d) ::
 [Ans. (b) One]  [Ans. (c) ,]
w

4. In python, ___ is an integer number which can 14. The ______ com can be used to delete an entire
be positive or negative. tuple
(a) Identifier (b) Keyword (a) del (b) delete
w

(c) Operators (d) Index value (c) remove (d) deletetuple


 [Ans. (d) Index value]  [Ans. (a) del]
5. ______ are used to access all elements from a 15. ______ is a powerful feature in python.
list.
(a) Tuple assignment (b) List assignment
(a) Branching (b) Loops
(c) Assignment statement (d) Set
(c) Alternative (d) Functions
 [Ans. (a) Tuple assignment]
 [Ans. (b) Loops]

123
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


16. Python return ____ value from a function 2. (a) List = { }
Unit III - Chapter 9

(a) Only One (b) Only Two (b) Set = [ ]


(c) Only Three (d) More than are (c) Tuple = ( )
 [Ans. (d) More than are] (d) Dictionary = ( ) [Ans. (c) Tuple = ( )]
17. In a nested tuple, each tuple is considered as a Choose the incorrect statement

m
(n)_____ 1. (i) A list in python is not a sequence data type
(a) Function (b) Tuple (ii) The elements of list should be specified with
(c) List (d) Set in [ ]
 [Ans. (b) Tuple] (iii) A list can be immutable.

co
(iv) A list contains another list as an element
18. A list or tuple can be converted as set by using (a) i and iii (b) ii and iv
______ function. (c) ii and iii (d) i, ii and iv
(a) List () (b) Tuple ()  [Ans. (a) i and iii]
(c) Setlt () (d) Set ()

s.
2. (i) L  ist function does not takes the result of
 [Ans. (d) Set ()]
range ()
19. The function _____ is used to join to sets in (ii) Both the arguments are not optional in sort ()
python. (iii) List comprehension is a simplest way of

ok
(a) Join () (b) Union () creating sequence of elements
(c) Join set () (d) Set () (iv) Tuple values are immutable
 [Ans. (b) Union ()] (a) i and iv (b) ii and iii
(c) i and ii (d) iii only
20. The______ operator is used to find symmetric
 [Ans. (c) i and ii]
o
difference set operation in python
(a) | (b) ^ (c) & (d) @ 3. (i) List are immutable
ab

 [Ans. (b) ^] (ii) Tuples are mutable


21. The keys in a python dictionary is separated by (iii) Tuples are enclosed in [ ] and also ( )
a ____ (iv) Iterating list is faster than tuples.
(a) ; (b) : : (c) : (d) , (a) i, ii (b) i, iii, iv
 [Ans. (c) :] (c) ii, iv (d) All of these
ur

 [Ans. (d) All of these]


Choose the correct statement Choose the incorrect pair
1. (i) Th e append (), insert () and extend () 1. (a) + – union
functions are used to include more elements (b) ^ – Symmetric difference
.s

in a tuple. (c) – – Difference


(ii) The remove () and pop are used to delete (d) & – Intersection [Ans. (a) + – union]
elements from a set.
2. (a) List = [ ]
(iii) Creating a Tuple with are element is called
w

‘Singleton’ Tuple. (b) Tuple = { }


(c) Set = { }
(iv) A Dictionary is a collection of element of
sametype. (d) Dictionary = { } [Ans. (b) Tuple = { }]
w

(a) i and iii (b) ii and iv Very Short Answers 2 MARKS


(c) i and iv (d) iv only 1. Write the syntax of creating list. Give example.
 [Ans. (d) iv only]
Ans. Syntax:
w

Choose the correct pair


Variable = [element-1, element-2, element-3 ……
1. (a) – union
(b) – – intersection element-n]
Example :
(c) ^ – Symmetric difference Marks = [10, 23, 41, 75]
(d) & – Difference Fruits = [“Apple”, “Orange”, “Mango”, “Banana”]
 [Ans. (c) ^ – Symmetric difference] MyList = [ ]

124
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. What is nested list? Give example. 7. Write the output for the following code?
Ans. (i) Mylist contains another list as an element. list = [2, 4, 6]

Lists, Tuples, Sets and Dictionary


This type of list is known as “Nested List”. list [0:3] = [1, 3, 5]
Nested list is a list containing another list as for x in list:
an element. print (x)
(ii) Example : Ans. Output : 1

m
Mylist = [ “Welcome”, 3.14, 10, [2, 4, 6] ] 3
3. Fill up the following to get the output: 5
10, 23, 41, 75 8. Differentiate append () and extend () function.

co
Marks = [10, 23, 41, 75] Ans. In Python, append( ) function is used to add a
(i) single element and extend( ) function is used to
add more than one element to an existing list.
while i (ii) 4:
9. How will you insert elements in a list? Write
print ( (iii) ) the syntax.

s.
i = (iv) Ans. (i) To include an element at your desired
Ans. (i) i = 0 position, you can use insert ( ) function.
(ii) <
The insert( ) function is used to insert an

ok
element at any position of a list.
(iii) Marks [i]
(ii) Syntax :
(iv) i + 1
List.insert (position index, element)
4. Write a program to print all elements in the list 10. Write the syntax of append () and extend ()
using reverse indexing. function.
o
Ans. Marks = [10, 23, 41, 75]
Ans. Syntax :
i = -1 List.append (element to be added)
while i >= -4:
ab

List.extend ( [elements to be added])


print (Marks[i]) 11. Write the syntax of deleting elements from the
i = i + -1 list.
Output : Ans. Syntax :
75 del List [index of an element]
ur

41 # to delete a particular element


23 del List [index from : index to]
10 # to delete multiple elements
5. Write a program to display element in a list del List
.s

(“Physics”, “Chemistry”, “Biology”) using loop # to delete entire list


to get the output 12. How will you delete the elements from the list
Physics if the index value is not known?
Chemistry
w

Ans. The remove( ) function can also be used to delete


Biology one or more elements if the index value is not
Ans. MySubject = ["Physics", "Chemistry", "Biology"] known.
i=0 13. State the working of pop () and clear ()
w

while i < len(MySubject): function.


print (MySubject[i]) Ans. (i) pop( ) function : pop( ) function can also be
i=i+1 used to delete an element using the given
w

index value. pop( ) function deletes and


6. Write a syntax that shows the lists are mutable. returns the last element of a list if the index
Ans. Syntax: is not given.
List_Variable [index of an element] = Value to be (ii) clear ( ) function : The function clear( ) is
changed used to delete all the elements in list, it
List_Variable [index from : index to] = Values to deletes only the elements and retains the
 be changed list.

125
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


14. Write the output for the following code 21. What is the use of tuple () function? Give
Unit III - Chapter 9

(i) print (list (range (1, 11, 2))) example.


(ii) print (list (range(2, 11, 2))) Ans. (i) The tuple( ) function is used to create
Ans. Output : Tuples from a list. When you create a tuple
(i) [1, 3, 5, 7, 9] from a list, the elements should be enclosed
(ii) [2, 4, 6, 8, 10] within square brackets.

m
(ii) Example :
15. Write a python program to print the following
MyTup3 = tuple( [23, 45, 90] )
output [36, 49, 64, 81, 100]
>>> print(MyTup3)
Ans. s = []

co
(23, 45, 90)
for x in range (6, 11)
a=x**2 22. Write the output
s. append (a) tup = (10)
print (s) type (tup)

s.
tup1 = (10,)
16. Write a python program to generate the
type (tup)
squares of even numbers between 1 and 10
Ans. Output :
using the concept of list comprehensions.

ok
Ans. s = [x ** 2 for x in range (2, 11, 2)]
<class ‘int’>
print (s) <class ‘tuple’>

17. What is output for the following code? 23. Give an example of joining two tuples.
list = [‘T’, ‘T’, ‘A’, ‘S’, ‘L’] Ans. # Program to join two tuples
o
list. sort (reverse = false) Tup1 = (2,4,6,8,10)
print (list) Tup2 = (1,3,5,7,9)
Tup3 = Tup1 + Tup2
ab

Ans. Output :
[‘A’, ‘L’, ‘S’, ‘T’, ‘T’] print(Tup3)
Output :
18. Write a program that creates a list of numbers
(2, 4, 6, 8, 10, 1, 3, 5, 7, 9)
from 1 to 20 that are divisible by 4
Ans. divBy4=[ ] 24. Write a program to swap two values using
ur

tuple assignment.
for i in range(21):
Ans. a = int(input("Enter value of A: "))
if (i%4==0):
divBy4.append(i) b = int(input("Enter value of B: "))
print("Value of A = ", a, "\n Value of B = ", b)
.s

print(divBy4)
Output : (a, b) = (b, a)
[0, 4, 8, 12, 16, 20] print("Value of A = ", a, "\n Value of B = ", b)
w

19. What is Tuple in python? 25. How will you create a set using list or tuple?
Ans. Tuples consists of a number of values separated Give an example.
by comma and enclosed within parentheses. Ans. A list or Tuple can be converted as set by using
Tuple is similar to list, values in a list can be set( ) function. This is very simple procedure.
w

changed but not in a tuple. First you have to create a list or Tuple then,
20. Write the syntax of defining tuple. substitute its variable within set( ) function as
argument.
Ans. Syntax :
w

Example :
# Empty tuple
Tuple_Name = ( ) MyList=[2,4,6,8,10]
# Tuple with n number elements MySet=set(MyList)
Tuple_Name = (E1, E2, E2 ……. En) print(MySet)
# Elements of a tuple without parenthesis Output :
Tuple_Name = E1, E2, E3 ….. En {2, 4, 6, 8, 10}

126
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


26. Write the output. 3. How will you change the list elements in
A = {‘A’, 2, 4, ‘D’} Python? Give an example.

Lists, Tuples, Sets and Dictionary


B = {‘A’, ‘B’, ‘C’, ‘D’} Ans. In Python, the lists are mutable, which means
print (A | B) they can be changed. A list element or range
of elements can be changed or altered by using
print (A & B) simple assignment operator (=).

m
print (A - B) Example :
print (A ^ B) MyList = [1, 3, 5, 7, 9]
Ans. Output : print ("List Odd numbers... ")
{‘A’, 2, 4, ‘D’, ‘B’, ‘C’} for x in MyList:

co
{‘A’, ‘D’} print (x)
{2, 4} MyList[0:5] = 2,4,6,8,10
{2, 4, ‘B’,’C’} print ("List Even numbers... ")
27. Find the odd man out. Give reason for y in MyList:

s.
print (y)
(a) ^
4. What is the output for the following
(b)
code?
(c) + MyList = [2, 4, 5, 8, 10]

ok
(d) – print ("MyList elements before update... ")
Ans. (c) (+). Because + is not a set operations. for x in MyList:
print (x)
Short Answers 3 MARKS MyList[2] = 6
o
1. How will you find the length of a list? Explain print ("MyList elements after updation... ")
with an example. for y in MyList:
print (y)
ab

Ans. (i) The len( ) function in Python is used to


find the length of a list. (i.e., the number of Ans. Output :
elements in a list). MyList elements before update...
(ii) Usually, the len( ) function is used to set the 2
upper limit in a loop to read all the elements 4
ur

of a list. 5
(iii) If a list contains another list as an element, 8
len( ) returns that inner list as a single 10
element. MyList elements after updation...
.s

(iv) Example : Accessing single element 2


>>> MySubject = [“Tamil”, “English”, 4
 “Comp. Science”, “Maths”] 6
8
w

>>> len(MySubject)
4 10
5. What is the output of the following code?
2. Fill up the following program to get the output
(i) list = [34, 45, 48]
w

TECM.
print (list. append (80))
list = [‘T’, ‘E’, ‘C’, ‘M’]
(ii) list = [34, 45, 48]
i=0 print (list. extend (80, 90))
w

(i) while ________: (iii) list = [34, 98, 47, 55]


(ii) ________ (MySubject[i], _______) list. insert (3, 90)
(iii) ________ i = i + 1 print (list)
Ans. (i) i < len (list) Ans. Output :
(ii) print (i) 34, 45, 48, 80
(iii) end = ‘\t’ (ii) 34, 45, 48, 80, 90
(iii) [34, 98, 47, 90, 55]

127
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


6. Read the following program and write the 11. Write a program to define a list of countries
Unit III - Chapter 9

output according to the print statement that are a member of BRICS. Check whether a
mentioned county is member of BRICS or not.
list = [‘T’, ‘H’, ‘N’, ‘M’] Ans. country=["India", "Russia", "Srilanka", "China",
del list [1] "Brazil"]
(i) print (list) is_member = input("Enter the name of the

m
del list [1:3]
 country: ")
(ii) print (list)’
del list if is_member in country:
(iii) print (list) print(is_member, " is the member of

co
Ans. Output: BRICS")
(i) [‘T’,‘N’, ‘M’]’ else:
(ii) [‘T’ print(is_member, " is not a member of
(iii) Error BRICS")
7. Write the syntax of remove (), pop () and

s.
Output :
clear().
Enter the name of the country: India
Ans. Syntax :
(i) remove ( ) : List.remove(element) # to India is the member of BRICS
Output :

ok
delete a particular element
(ii) pop ( ) : List.pop(index of an element) Enter the name of the country: Japan
(iii) clear ( ) : List.clear( ) Japan is not a member of BRICS
8. Read the following and write the output given 12. Differentiate list and tuple.
by the print function mentione(d)
Ans. (i) In a list, elements are defined within square
o
list = [12, 89, 34, 79, 80]
brackets, whereas in tuples, they may be
(i) print (list. remove (34))
enclosed by parenthesis.
(ii) print (list. pop (1))
ab

(iii) print (list. clear ()) (ii) The elements of a tuple can be even defined
Ans. Output : without parenthesis.
(i) 12, 89, 79, 80 (iii) Whether the elements defined within
(ii) 12, 79, 80 parenthesis or without parenthesis, there is
(iii) [] no differente in it's function.
ur

9. Write a note on list comprehensions. 13. Explain with an example how will you create a
Ans. (i) List comprehension is a simplest way of tuple with a single element.
creating sequence of elements that satisfy a Ans. (i) While creating a tuple with a single element,
certain condition. add a comma at the end of the element.
.s

(ii) Syntax : (ii) In the absence of a comma, Python will


List = [ expression for variable in range ] consider the element as an ordinary data
(iii) Example : Generating squares of first 10 type; not a tuple. Creating a Tuple with one
w

natural numbers using the concept of List element is called “Singleton” tuple.
comprehension. (iii) Example :
>>> squares = [ x ** 2 for x in range(1,11) ]
>>> MyTup4 = (10)
>>> print (squares)
w

>>> type(MyTup4)
Output :
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] <class 'int'>
10. Write the output for the following. >>> MyTup5 = (10,)
>>> type(MyTup5)
w

list = [36, 12, 12]


(i) print (list. count (12)) <class 'tuple'>
(ii) print (list. index (12)) 14. Write the output for the following.
(iii) print (list. reverse ()) Tup = (12, 78, 91, ‘A’, ‘B’, 3, 69)
Ans. Output : 1. print (Tup1 [2:5]) _______1
(i) 2
2. print (Tup [:5]) _________2
(ii) 1
3. print (Tup [4:]) _________3
(iii) [12, 12, 36]

128
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. print (Tup [:]) __________4 18. Write the equivalent python statement for the
5. print (Tup) ____________ 5 following

Lists, Tuples, Sets and Dictionary


Ans. Output : (i) C = A | B
1. (91, ‘A’, ‘B’) (ii) C = A & B
2. (12, 78, 91, ‘A’, ‘B’)
(iii) C = A – B

m
3. (‘B’, 3, 69)
4. (12, 78, 91, 'A’, ‘B’, 3, 69) (iv) C = A ^ B
5. (12, 78, 91, ‘A’, ‘B’, 3, 69) Ans. (i) C = A. union (B)
(ii) C = A. intersection (B)

co
15. Write a note on Tuple assignment.
Ans. Tuple assignment is a powerful feature in (iii) C = A. difference (B)
Python. It allows a tuple variable on the left of the
(iv) C = A. symmetric _ difference (B)
assignment operator to be assigned to the values
on the right side of the assignment operator. 19. Write a note on dictionary comprehension.

s.
Each value is assigned to its respective variable. Ans. (i) In Python, comprehension is another way
a b c
of creating dictionary. The following is the
= 34 90 76
syntax of creating such dictionary.

ok
(ii) Syntax :
Example : Dict = { expression for variable in sequence
>>> (a, b, c) = (34, 90, 76)  [if condition] }
>>> print(a,b,c) (iii) The if condition is optional and if specified,
o
34 90 76 only those values in the sequence are
16. How will create a set in python? Give an evaluated using the expression which
ab

example. satisfy the condition.


Ans. (i) A set is created by placing all the elements (iv) Example :
separated by comma within a pair of curly Dict = { x : 2 * x for x in range(1,10)}
brackets. The set( ) function can also used
to create sets in Python. Output of the above code is
ur

(ii) Syntax : {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16,


Set_Variable = {E1, E2, E3 …….. En}  9: 18}
(iii) Example : 20. Fill up the blanks in the following.
.s

>>> S1={1,2,3,'A',3.14} (i) Dict = {'Roll No' : 12001, 'SName' :


>>> print(S1)  'Meena','Mark1' : 98, 'Marl2' : 86}
{1, 2, 3, 3.14, 'A'}
print("Dictionary elements before
w

>>> S2={1,2,2,'A',3.14}  deletion: \n", Dict)


>>> print(S2)
del Dict['Mark1] # ____________
{1, 2, 'A', 3.14}
(ii) print("Dictionary elements after deletion
w

17. How will delete an entire tuple? Give an


example.  of a element: \n", Dict)
Ans. (i) To delete an entire tuple, the del command Dict.clear() # ____________
can be used.
w

(iii) print("Dictionary after deletion of all


(ii) Syntax : del tuple_name  elements: \n", Dict) del Dict
(iii) Example : print(Dict) # ____________
Tup1 = (2,4,6,8,10)
Ans. (i) # Deleting a particular element
print("The elements of Tup1 is ", Tup1)
(ii) # Deleting all elements
del Tup1
print (Tup1) (iii) # Deleting entire dictionary

129
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


21. Write a note on the following function used in (vi) The Python reads the for loop and print
statements like English: “For (every)
Unit III - Chapter 9

list.
Ans.
element (represented as x) in (the list
of) Marks and print (the values of the)
max( ) Returns max MyList=[21,76,98,23] elements”.
the (list) print(max(MyList)) 2. Explain remove (), pop () and clear () used in

m
maximum Output : list with an example.
value in a Ans. remove ( ) :
98
list. (i) The remove( ) function can also be used to

co
min( ) Returns min MyList=[21,76,98,23] delete one or more elements if the index
the (list) print(min(MyList)) value is not known.
minimum Output : (ii) Syntax:
value in a List.remove(element) # to delete a particular
21
list. element

s.
(iii) Example :
sum( ) Returns sum MyList=[21,76,98,23]
>>>MyList=[12,89,34,'Kannan', 'Gowri
the sum of (list) print(sum(MyList))
 sankar', 'Lenin']
values in a Output : >>> print(MyList)

ok
list.
218 [12, 89, 34, 'Kannan', 'Gowrisankar',
'Lenin']
Long Answers 5 MARKS >>> MyList.remove(89)
>>> print(MyList)
1. How will you access elements of a list using for [12, 34, 'Kannan', 'Gowrisankar',
o
loop? Explain with an example. 'Lenin']
Ans. (i) In Python, 'for loop' is used to access all the pop ( ):
ab

elements in a list one by one. This is just (i) pop( ) function can also be used to delete
like the for keyword in other programming an element using the given index value.
language such as C++. pop( ) function deletes and returns the last
element of a list if the index is not given.
(ii) Syntax :
(ii) pop( ) function is used to delete a particular
ur

for index_var in list: element using its index value, as soon as the
print (index_var) element is deleted.
(iii) Here, index_var represents the index value (iii) The pop( ) function shows the element
of each element in the list. Python reads which is deleted. pop( ) function is used
.s

this “for” statement like English: “For to delete only one element from a list.
(every) element in (the list of) list and print Remember that, del statement deletes
(the name of the) list items” multiple elements.
(iv) Syntax: List.pop(index of an element)
w

(iv) Example :
(v) Example :
Marks=[23, 45, 67, 78, 98]
>>> MyList.pop(1)
for x in Marks: 34
w

print( x ) >>> print(MyList)


Output : [12, 'Kannan', 'Gowrisankar', 'Lenin']
23 clear ( ) :
w

45 (i) The function clear( ) is used to delete all the


67 elements in list, it deletes only the elements
78 and retains the list.
98 (ii) clear( ) function removes only the elements
(v) In the above example, Marks list has 5 and retains the list. When you try to print
elements; each element is indexed from 0 the list which is already cleared, an empty
to 4. square bracket is displayed without any
elements, which means the list is empty.
130
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iii) Syntax: 4. Write a python program to read marks of six
List.clear( ) subjects and to print the marks scored in each

Lists, Tuples, Sets and Dictionary


Example : subject and show the total marks.
>>> MyList.clear( ) Ans. Program :
>>> print(MyList) marks=[]
subjects=['Tamil', 'English', 'Physics', 'Chemistry',

m
[]
'Comp. Science', 'Maths']
3. Explain the following function used in list for i in range(6):
function with an example. m=int(input("Enter Mark = "))
(i) copy ()

co
marks.append(m)
(ii) count () for j in range(len(marks)):
(iii) index () print("{ }. { } Mark =
(iv) reverse ()  { } ".format(j1+,subjects[j],marks[j]))
Ans. (i) copy ( ) : Returns a copy of the list. print("Total Marks = ", sum(marks))

s.
Syntax : List.copy( ) Output :
Example : Enter Mark = 45
MyList=[12, 12, 36] Enter Mark = 98

ok
x = MyList.copy() Enter Mark = 76
print(x) Enter Mark = 28
Output : Enter Mark = 46
[12, 12, 36] Enter Mark = 15
(ii) count () : Returns the number of similar 1. Tamil Mark = 45
o
elements present in the last. 2. English Mark = 98
Syntax: List.count(value) 3. Physics Mark = 76
ab

Example : 4. Chemistry Mark = 28


MyList=[36 ,12 ,12] 5. Comp. Science Mark = 46
x = MyList.count(12) 6. Maths Mark = 15
print(x) Total Marks = 308
ur

Output : 5. Write a python program to read prices of 5


2 items in a list and then display sum of all the
(iii) index ( ) : Returns the index value of the prices, product of all the prices and find the
first recurring element. average.
.s

Syntax: List.index(element) Ans. Program :


Example : items=[]
MyList=[36 ,12 ,12] prod=1
w

x = MyList.index(12) for i in range(5):


print(x) print ("Enter price for item { } : 
Output : ".format(i+1))
w

0 p=int(input())
(iv) reverse ( ) : Reverses the order of the items.append(p)
element in the list. for j in range(len(items)):
Syntax: List.reverse( ) print("Price for item { } =
w

Example :  Rs. { }".format(j+1,items[j]))


MyList=[36 ,23 ,12] prod = prod * items[j]
MyList.reverse() print("Sum of all prices = Rs.", sum(items))
print(MyList) print("Product of all prices = Rs.", prod)
Output : print("Average of all prices = Rs.",sum(items)/
[12 ,23 ,36] len(items))

131
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Output : Enter Monthly Salary of Employee 3 Rs.:
Unit III - Chapter 9

Enter price for item 1 : 12500


5 Enter Monthly Salary of Employee 4 Rs.:
Enter price for item 2 : 5750
10 Enter Monthly Salary of Employee 5 Rs.:
Enter price for item 3 : 8000

m
15 Annual Salary of Employee 1 is:Rs. 36000
Enter price for item 4 : Annual Salary of Employee 2 is:Rs. 114000
20 Annual Salary of Employee 3 is:Rs. 150000

co
Enter price for item 5 : Annual Salary of Employee 4 is:Rs. 69000
25 Annual Salary of Employee 5 is:Rs. 96000
Price for item 1 = Rs. 5 2 Employees out of 5 employees are earning
Price for item 2 = Rs. 10  more than Rs. 1 Lakh per annum
Price for item 3 = Rs. 15 7. Write a program to create a list of numbers

s.
Price for item 4 = Rs. 20 in the range 1 to 10. Then delete all the even
Price for item 5 = Rs. 25 numbers from the list and print the final list.
Sum of all prices = Rs. 75 Ans. Program :

ok
Product of all prices = Rs. 375000 Num = []
Average of all prices = Rs. 15.0 for x in range(1,11):
6. Write a python program to count the number Num.append(x)
of employees earning more than 1 lakh per print("The list of numbers from 1 to 10 = ", Num)
annum. The monthly salaries of n number of for index, i in enumerate(Num):
o
employees are given. if(i%2==0):
Ans. Program : del Num[index]
ab

count=0 print("The list after deleting even numbers = ",


n=int(input("Enter no. of employees: ")) Num)
print("No. of Employees",n) Output :
salary=[] The list of numbers from 1 to 10 = [1, 2, 3, 4, 5,
for i in range(n):  6, 7, 8, 9, 10]
ur

print("Enter Monthly Salary of Employee The list after deleting even numbers = [1, 3, 5,
 { } Rs.: ".format(i+1))  7, 9]
s=int(input()) 8. Write a program to create a list of numbers
salary.append(s) in the range 1 to 10. Then delete all the odd
.s

for j in range(len(salary)): numbers from the list and print the final list.
annual_salary = salary[j] * 12 Ans. Program :
print ("Annual Salary of Employee { } n = []
w

 is:Rs. { }".format(j+1,annual_salary)) for x in range (1, 11)


if annual_salary >= 100000: n = append (x)
count = count + 1 for x, i in enumerate (n):
print("{ } Employees out of { } employees are if (i %2 ! = 0):
w

earning more than Rs. 1 Lakh per annum".for del n [x]


 mat(count, n)) print (n)
Output :
9. Write a program to generate in the Fibonacci
w

Enter no. of employees: 5


No. of Employees 5 series and store it in a list. Then find the sum
Enter Monthly Salary of Employee 1 Rs.: of all values.
Ans. Program :
3000
Enter Monthly Salary of Employee 2 Rs.: a=-1
9500 b=1
n=int(input("Enter no. of terms: "))

132
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


i=0 Output :
sum=0

Lists, Tuples, Sets and Dictionary


Enter the Radius: 5
Fibo=[]
while i<n: Area of the circle = 78.5
s=a+b Circumference of the circle = 
Fibo.append(s)

m
31.400000000000002
sum+=s
a=b 12. Write a program that generate a set of prime
b=s numbers and another set of even numbers.

co
i+=1 Demonstrate the result of union, intersection,
print("Fibonacci series upto "+ str(n) +" terms is difference and symmetric difference
 : " + str(Fibo)) operations.
print("The sum of Fibonacci series: ",sum) Ans. Program :
Output :

s.
Enter no. of terms: 10 even=set([x*2 for x in range(1,11)])
Fibonacci series upto 10 terms is : [0, 1, 1, 2, 3, 5, primes=set()
 8, 13, 21, 34] for i in range(2,20):

ok
The sum of Fibonacci series: 88
10. Explain with an example how will you return j=2
multiple values in tuples. f=0
Ans. (i) A function can return only one value at a
while j<i/2:
time, but Python returns more than one
o
value from a function. Python groups if i%j==0:
multiple values and returns them together. f=1
(ii) Example : Program to return the maximum
ab

as well as minimum values in a list j+=1


def Min_Max(n): if f==0:
a = max(n) primes.add(i)
b = min(n)
print("Even Numbers: ", even)
ur

return(a, b)
Num = (12, 65, 84, 1, 18, 85, 99) print("Prime Numbers: ", primes)
(Max_Num, Min_Num) = Min_Max(Num) print("Union: ", even.union(primes))
print("Maximum value = ", Max_Num)
print("Intersection: ", even.intersection(primes))
.s

print("Minimum value = ", Min_Num)


(iii) Output : print("Difference: ", even.difference(primes))
Maximum value = 99 print("Symmetric Difference: ", even.symmetric_
Minimum value = 1
w

difference(primes))
11. Write a program using a function that returns
the area and circumference of a circle whose Output :
radius is passed as an argument. Two values Even Numbers: {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
w

using tuple assignment.


Prime Numbers: {2, 3, 4, 5, 7, 11, 13, 17, 19}
Ans. Program :
pi = 3.14 Union: {2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 16,
 17, 18, 19, 20}
w

def Circle(r):
return (pi*r*r, 2*pi*r) Intersection: {2, 4}
radius = float(input("Enter the Radius: "))
Difference: {6, 8, 10, 12, 14, 16, 18, 20}
(area, circum) = Circle(radius)
print ("Area of the circle = ", area) Symmetric Difference: {3, 5, 6, 7, 8, 10, 11, 12,
print ("Circumference of the circle = ", circum)  13, 14, 16, 17, 18, 19, 20}


133
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

  
Chapter PYTHON CLASSES AND
10 OBJECTS

m

co
CHAPTER SNAPSHOT
10.1 Introduction
10.2 Defining classes

s.
10.3 Creating Objects
10.4 Accessing Class Members
10.5 Class Methods

ok
10.6 Constructor and Destructor in Python
10.7 Public and Private Data Members

Evaluation 5. A private class variable is prefixed with


o
(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]
1. Which of the following are the key features of (a) __init__( ) (b) __dest__( )
an Object Oriented Programming language? (c) __rem__( ) (d) __del__( )
ur

(a) Constructor and Classes  [Ans. (d) __del__( )]


(b) Constructor and Object
7. Which of the following class declaration is
(c) Classes and Objects
correct? [PTA-6]
(d) Constructor and Destructor
.s

 [Ans. (c) Classes and Objects] (a) class class_name


(b) class class_name<>
2. Functions defined inside a class: (c) class class_name:
(d) class class_name[ ]
w

(a) Functions (b) Module


(c) Methods (d) section  [Ans. (c) class class_name:]
 [Ans. (c) Methods]
8. Which of the following is the output of the
w

3. Class members are accessed through which following program?


operator? class Student:
(a) & (b) . (c) # (d) %
def __init__(self, name):
 [Ans. (b) . ]
w

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

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


9. Which of the following is the private class (ii) Constructor function will automatically
variable? [PTA-2] executed when an object of a class is created.

Python Classes and Objects


(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>

m
 [HY-2019]
5. What is the purpose of Destructor? [PTA-2]
(a) Constructor (b) Destructor
(c) Initialize (d) Instantiation Ans. (i) Destructor is also a special method gets
 [Ans. (d) Instantiation] executed automatically when an object exit

co
from the scope.
Part - II (ii) In Python,_del_() method is used as
Answer the following questions destructor.
 (2 marks) General format :
def_del_(self):

s.
1. What is class? [PTA-1] <statements>
Ans. (i) Class is the main building block in Python.
Part - III
(ii) Class is a template for the object.
Answer the following questions

ok
(iii) Object is a collection of data and function
that act on those data.
 (3 marks)
1. What are class members? How do you define it?
(iv) Objects are also called as instances of a class
 [PTA-1]
or class variable.
Ans. Variables defined inside a class are called as “Class
o
2. What is instantiation? [PTA-6] Variable” and functions are called as “Methods”.
Ans. Once a class is created, next to create an object Class variable and methods are together known
ab

or instance of that class. The process of creating as members of the class. The class members
object is called as “Class Instantiation”. should be accessed through objects or instance
Syntax : of class. A class can be defined anywhere in a
Object_name = class_name( ) Python program.
3. What is the output of the following program? Syntax for Defining a Class :
ur

class Sample: class class_name :


__num=10 statement_1
def disp(self): statement_2
.s

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

Ans. Output : 2. Write a class with two private class variables


>>> and print the sum using a method. [PTA-2]
10 Ans. Code :
w

line 7, in <module> class Sample :


print(S._num) def_init_(self, n1, n2):
AttributeError : 'Sample' object has no attribute self._n1=n1
w

'_num' 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)  print ("Class Variable 2:", self._n2)
with double underscore in Python act as a S=Sample (5,10)
Constructor. S.sum()

135
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Output : (iii) In Python, __del__() method is used as
Unit III - Chapter 10

>>> destructor.
Class Variable 1 : 5 General format of constructor :
Class Variable 2 : 10 def__del__(self):
Sum : 15 <statements>
>>> Part - IV

m
3. Find the error in the following program to get Answer the following questions
the given output?  (5 marks)
class Fruits:

co
1. Write a menu driven program to add or delete
def __init__(self, f1, f2): stationary items. You should use dictionary to
self.f1=f1 store items and the brand.
self.f2=f2
Ans. Code :
def display(self):
stationary = {}

s.
print("Fruit 1 = %s, Fruit 2 = %s"
 %(self.f1, self.f2)) print("\n1.Add Item \n2. Delete item \n3.Exit")
F = Fruits ('Apple', 'Mango') ch=int(input("\nEnter your choice:"))
del F.display while(ch==1) or (ch==2):

ok
F.display() if(ch==1)
Output : n=int(input("\nEnter the Number of
Fruit 1 = Apple, Fruit 2 = Mango  Items to be added in the Dictionary:"))
Ans. In line No.8, del F.display will not come. for i in range(n):
o
4. What is the output of the following program? item=input("\nEnter an Item Name:")
class Greeting: brand=input("\nEnter the Brand Name:")
ab

def __init__(self, name): stationary[item]=brand


self.__name = name print(stationary)
def display(self): elif(ch==2):
print("Good Morning ", self.__name) ritem=input("\nEnter the item to be
obj=Greeting('Bindu Madhavan')  removed from the Dictionary:")
ur

obj.display()
stationary.pop(ritem)
Ans. Good Morning Bindu Madhavan
print(stationay)
5. How do define constructor and destructor in ch=int(input("\nEnter your choice:"))
.s

Python? [PTA-4] Output :


Ans. Constructor : 1. Add Item
(i) Constructor is the special function that 2. Delete item
is automatically executed when an object 3. Exit
w

of a class is created. In Python, there is a Enter your choice : 1


special function called “init” which act as a Enter the Number of Items to be added in the
Constructor.  stationary shop : 2
w

(ii) It must begin and end with double Enter an Item Name : Pen
underscore. Enter the Brand Name : Rorito
(iii) Constructor function will automatically Enter an Item Name : Pencil
executed when an object of a class is created. Enter the Brand Name : Camlin
w

General format of constructor : {'Pen' : 'Rorito', 'Pencil' : 'Camlin'}


def__init__(self, [args ................]): Enter your choice : 2
<statements> Enter the item to be removed from the Dictionary
Destructor :  : Pen
(i) Destructor is also a special method gets {'Pencil': 'Camlin'}
executed automatically when an object exit Enter your choice : 3
from the scope.

136
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Write a menu driven program to read, display,
Hands on Experience add and subtract two distances.

Python Classes and Objects


1. Write a program using class to store name and Ans. class Dist :
marks of students in list and print total marks. def__init__(self):
Ans. Class stud : self.dist 1=0
def__init__(self): self.dist 2=0

m
self.name=" " def read(self):
self.m1=0 self.dist 1 =int(input("Enter distance 1"))
self.m2=0 sefl.dist 2 =int(input("Enter distance 2"))

co
self.tot=0 def disp(self):
def gdata(self): print("distance 1", self.dist 1)
self.name = input("Enter your name") print("distance 2", self.dist 2)
self.m1 = int(input("Enter marks 1")) def add(self):
self.m2 = int(input("Enter marks 2")) print("Total distance", self.dist 1 + self.dist

s.
self.tot = self.m1 + self.m2 2)
def disp(self): def sub(self):
print(self.name) print("Subtracted distance", self.dist 1-self.
print(self.m1) dist 2)

ok
print(self.m2) d=Dist()
print(self.tot) choi = "y"
mlist = [] while(choi =="y"):
st = stud() print("1. accept\n2. Display \n3. Total \n4.
o
st. gdata() Subtract")
mlist.append(st) ch = int(input("Enter your choice"))
for x in mlist : if(ch==1):
ab

x. disp() d.read()
Output : elif(ch==2)
Enter your name Ram d.disp()
Enter marks 1 100 elif(ch==3):
ur

Enter marks 2 100 d.add()


Ram 100 100 200 elif(ch==4):
2. Write a program using class to accept three d.sub()
sides of a triangle and print its area. else:
.s

Ans. Class Tr: print("Invalid Input ...")


def__init__(self, a, b, c): choi = input("Do you want to continue")
self.a = float(a) Output :
slef.b = float(b) 1. Accept
w

self.c = float(c) 2. Display


def area(self): 3. Add
s = (self.a + self.b + self.c)/2 4. Subtract
w

return((s*(S.self.a)*(s.self.b)*(s.self.c)**0.5) Enter your choice : 1


a = input("Enter side 1 :") Enter distance 1 : 100
b = input("Enter side 2 :") Enter distance 2 : 75
c = input("Enter side 3 :")
w

Do you want to continue .. y


ans = Tr(a,b,c) 1. Accept
print(ans.area()) 2. Display
Output : 3. Add
Enter side 1 : 3 4. Subtract
Enter side 2 : 4 Enter your choice : 3
Enter side 3 : 5 Total distances : 175
6.0
137
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Do you want to continue ..y 3 MARKS
Unit III - Chapter 10

1. Accept
1. What is Public and Private data member in
2. Display Python? [PTA-3]
3. Add Ans. (i) The variables which are defined inside the
4. Subtract class is public by default. These variables

m
Enter your choice : 2 can be accessed anywhere in the program
Enter distance 1 : 100 using dot operator.
Enter distance 2 : 75 (ii) A variable prefixed with double underscore
Do you want to continue ..y becomes private in nature. These variables

co
1. Accept can be accessed only within the class.
2. Display 5 MARKS
3. Add
4. Sub 1. Find the output of the following Python code
 [PTA-1]

s.
Enter your choice : 4
class Sample:
Subtracted distance : 25
num=0
Do you want to continue .. N def __init__(self, var):

ok
PTA Questions and Answers Sample.num+=1
self.var=var
1 MARKS print("The object value is = ", var)
print("The count of object created
1. In Python the class method must have which
 = ", Sample.num)
o
named argument as first argument? [PTA-3]
S1=Sample(15)
(a) self (b) rec
S2=Sample(35)
ab

(c) global (d) key S3=Sample(45)


 [Ans. (a) self] Ans. In the program, class variable num is shared
2. The function defined inside a class is called as by all three objects of the class Sample. It is
______. [PTA-4] initialized to zero and each time an object is
created, the num is incremented by 1. Since, the
ur

(a) Attribute (b) Parameter


(c) Arguments (d) Methods variable shared by all objects, change made to
num by one object is reflected in other objects
 [Ans. (d) Methods]
as well.
3. The symbol of project in relational algebra of 2. What will be the output of the following
.s

DBMS : [PTA-5] Python code? [PTA-2]


(a) σ (b) П (c) ∩ (d) ∪ class String
 [Ans. (b) П]
w

def__init__(self):
2 MARKS self.uppercase=0
self.lowercase=0
1. Write the syntax of class instantiation.[PTA-5]
self.vowels=0
w

Ans. Syntax :
self.consonants=0
object_name = class_name()
Note that the class instantiation uses function self.spaces=0
notation. ie.class_name with. self.string=""
w

def getstr(self):
2. Write the general format of slicing operation. self.string= "Welcome to
 [PTA-6] Puducherry"
Ans. General format of slice operation: def count_upper(self):
str[start:end] for ch in self.string:
if (ch.isupper()):
self.uppercase+=1
138
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


def count_lower(self): 3. Rewrite the following Python program to get
for ch in self.string: the given output: [PTA-3]

Python Classes and Objects


if (ch.islower()): OUTPUT :
self.lowercase+=1 Enter Radius: 5
def count_vowels(self): The area = 78.5
for ch in self.string:

m
The circumference = 34.10
if (ch in ('A', 'a', 'e', 'E', 'i', 'l', CODE :
 'o', 'O', 'u', 'U')):
Class circle( )
self.vowels+=1
pi=3.14

co
def count_consonants(self):
for ch in self.string: def__init__(self, radius):
if (ch not in ('A', 'a', 'e', 'E', 'i', self=radius
 'I', 'o', 'O', 'u', 'U', ' ')): DEF area(SELF):
self.consonants+=1 Return

s.
def count_space(self): Circle.pi + (self.radius * 2)
for ch in self.string: Def circumference (self):
if (ch==" "): Return 2*circle.pi * self.radius

ok
self.spaces+=1 r = input("Enter radius= ")
def execute(self):
c = circle(r)
self.count_upper()
self.count_lower() print "The Area: ", c.area( )
print("The circumference=", c)
o
self.count_vowels()
self.count_consonants() Ans. Class circle:
self.count_space() pi=3.14
ab

def display(self): def__init__(self, radius):


print("The given string self.radius = radius
contains...")
print("%d Uppercase def area(self):
return circle.pi*(self.radius**2)
ur

letters"%self.uppercase)
print("%d Lowercase def circumference(self):
letters"%self.lowercase) return2*circle.pi*self.radius
print(%d Vowels"%self.vowels) r=int(input("Enter Radius:"))
.s

print("%d Consonants"%self.
c = circle(r)
consonants)
print("%d Spaces"%self.spaces) print("The Area= ", c.area( ))
S = String() print("The circumference = ", c.circumference)
w

S.getstr()
Government Exam Questions and Answers
S.execute()
S.display() 1 MARK
w

Ans. Output :
Enter a string : Welcome to Puducherry 1. A variable prefixed with double underscore is
The given string contains  [Govt. MQP-2019]
w

5 uppercase letters (a) private


24 lowercaase letters (b) public
12 vowels (c) protected
17 consonants (d) static[Ans. (a) private]
3 spaces

139
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3 MARKS 5 MARKS
Unit III - Chapter 10

1. What is the output of the following program? 1. How will you create the class, and objects in
class Greeting: [Govt. MQP-2019] python. [QY-2019]
def__init__(self, name): Ans. (i) In Python, a class is defi ned by using the
self.__name = name keyword class. Every class has a unique

m
name followed by a colon ( : ).
def display(self):
Syntax:
print("Good Morning", self.__name)
class class_name:
obj=Greeting('Tamil Nadu') statement_1

co
obj.display() statement_2
Ans. Good Morning Tamil Nadu …………..
2. What is Constructor? [QY-2019] …………..
Ans. Constructor is the special function that is statement_n
automatically executed when an object of a class (ii) 
Where, statement in a class definition

s.
is created. In Python, there is a special function may be a variable declaration, decision
called “init” which act as a Constructor. It must control, loop or even a function definition.
begin and end with double underscore. This Variables defined inside a class are called as

ok
function will act as an ordinary function; but only “Class Variable” and functions are called as
difference is, it is executed automatically when “Methods”. Class variable and methods are
the object is created. This constructor function together known as members of the class.
can be defined with or without arguments. This
The class members should be accessed
method is used to initialize the class variables.
through objects or instance of class. A
o
General format of __init__ method (Constructor
function) class can be defined anywhere in a Python
def __init__(self, [args ……..]): program.
ab

<statements>
additional questions and Answers
3. Write a Python program to check and print if
the given number is odd or even using class. Choose the Correct Answer 1 MARK
Ans. class Odd_Even: [HY-2019]
1. Which of the following is not an object
ur

even = 0 #class variable


oriented language?
def check(self, num):
if num%2==0: (a) C (b) C++
print(num," is Even number") (c) Java (d) Python
.s

else:  [Ans. (a) C]


print(num," is Odd number") 2. Which of the following called as instances of a
n=Odd_Even() class or class variable?
w

x = int(input("Enter a value: ")) (a) Methods


n.check(x) (b) Objects
4. What is the output of the following program? (c) Functions
w

class Greeting: [Govt. MQP-2019] (d) Datatypes [Ans. (b) Objects]


def__init__(self, name): 3. Functions of the class are called as
self.__name = name (a) Methods
w

def display(self): (b) Members


print(“Good Morning”, self.__ (c) Variables
name) (d) Loog [Ans. (a) Methods]
obj=Greeting(‘Tamil Nadu’)
obj.display() 4. In Python, every class name followed by
Ans. Output : (a) ; (b) : (c) : : (d) .
Good Morning Tamil Nadu  [Ans. (b) :]

140
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5. Which of the following with a valid class 13. Which of the following argument values
definition? automatically by python?

Python Classes and Objects


(a) Class classname () statement_1 (a) self (b) this
(b) Class classname : : statement_1 (c) class (d) object
(c) Class classname statement_1  [Ans. (a) self]
(d) Class classname statement_1 14. How many argument can be taken by Python

m
 [Ans. (c) Class classname statement_1] method even when a method is defined with
one argument?
6. Which of the following is valid syntax for (a) 1 (b) 3 (c) 2 (d) 4
crating objects?

co
 [Ans. (c) 2]
(a) objectname = classname ()
15. Which of the following is automatically
(b) objectname : classname () executed when an object of a class is created?
(c) objectname = classname (a) constructor (b) destructor
(d) classname = Objectname ()
(c) class (d) members

s.
 [Ans. (c) objectname = classname]
 [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?

ok
(a) . (b) : (c) ; (d) , (a) int (b) inti
 [Ans. (a) .] (c) classname (d) init
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
o
(c) Dictionary (d) None of these (a) _ _ and _ _ (b) _ _ and _ _
 [Ans. (d) None of these] (c) + + and + + (d) + - and - +
ab

9. Which of the following is valid syntax of  [Ans. (a) _ _ and _ _]


accessing class members 18. Which of the following is used to initialize the
(a) objectname = classmember () class variables?
(b) objectname . classmember () (a) Destructor (b) Object
(c) objectname . classmember (c) Constructor (d) Classmember
ur

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


 [Ans. (b) objectname . classmember ()] 19. Which of the following gets executed
automatically when an object exit from the
10. Write the output for the following scope?
.s

class test (a) Destructor (b) Constructor


x, y = 10, 5 (c) Class (d) Object
s = test ()  [Ans. (a) Destructor]
w

print (s. x + s. y) 20. By default, the class variables are


(a) 10 (b) 5 (c) 15 (d) 105
(a) Private (b) Public
 [Ans. (c) 15]
(c) Protected (d) Method
w

11. Which position of the argument named self in  [Ans. (b) Public]
python class method? 21. Which of the following is a valid private
(a) First (b) Second variable in python?
(c) Third (d) Last (a) - i (b) i - (c) - - i (d) i - -
w

 [Ans. (a) First]  [Ans. (c) - - i]


12. Which argument doesn’t need a value when we 22. Which of the following variables can be
call the method? accessed only within the class?
(a) this (b) self (a) Protected (b) Public
(c) var (d) first (c) Private (d) None of these
 [Ans. (b) self]  [Ans. (d) None of these]

141
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose and filling the blanks 10. Constructor must begin and with double
Unit III - Chapter 10

1. ____ and ___ are the key features of object ______


oriented programming. (a) Colon (b) Semicolon
(a) List and tuples (c) Dot (d) Underscore
(b) Set and dictionary  [Ans. (d) Underscore]

m
(c) Classes and objects 11. In Python, _____ method is used as destructor.
(d) Variables and methods (a) - - init - - () (b) - - des - - ()
 [Ans. (c) Classes and objects] (c) - - del - - ()
2. ____ is the main building block in python. (d) - - destructor - - () [Ans. (b) - - des - - ()]

co
(a) Objects (b) Methods 12. A variable prefixed with _____ become private
(c) Constructors (d) Class in nature.
 [Ans. (d) Class] (a) double underscore (b) double colon
3. Class is a template for the _____ (c) double dot (d) double hyphen

s.
(a) Method (b) Members  [Ans. (a) double underscore]
(c) Object (d) Destructor
 [Ans. (c) Object]
Choose the correct statement
1. (a) objectname.classmember()

ok
4. ______ may be a variable declaration, decision
control, loop or even a function definition. (b) objectname.classmember
(a) Class members (c) objectname().classmember
(b) Class instantiation (d) objectname : classmember
(c) Class method  [Ans. (b) objectname.classmember]
o
(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?
ab

class. (a) - - init - -


(a) Operator (b) Identifier (b) - - init - - ()
(c) Object (d) Keyword (c) - - classname - - ()
 [Ans. (d) Keyword] (d) - - classname - - () [Ans. (b) - - init - - ()]
6. Class variable and methods are together
ur

3. (a) objectname = classname


known as ______ of the class.
(b) objectname : classname ()
(a) Objects (b) Functions
(c) objectname = classname ()
(c) Statements (d) Members
(d) objectname : : classname ()
 [Ans. (d) Members]
.s

 [Ans. (c) objectname = classname ()]


7. The ______ of the class should be accessed
through instance of a class. Choose the incorrect statement
(a) Objects (b) Members 1. (i) Th e process of creating object is called “Class
w

(c) Functions (d) Tuples definition”


 [Ans. (b) Members] (ii) The class members are accessed using dot (.)
8. The process of creating object is called as ____ operator.
w

(a) Class definition (b) Class declaration (iii) The first argument of the class method is not
(c) Class instantiation (d) Class objects self.
 [Ans. (c) Class instantiation]
(iv) The method argument defined with one
w

9. When class variable declared within class, argument it takes two arguments with
methods must be prefixed by the _______ and
default.
______
(a) classnam, : (b) classname, . (a) i and iv (b) ii and iii
(c) :, classname (c) iv only (d) i and iii
(d) classname, objectname  [Ans. (d) i and iii]
 [Ans. (b) classname, .]

142
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. (i) C  onstructor executed automatically when Short Answers 3 MARKS
the object is created

Python Classes and Objects


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

m
(iv) Construct is used to initialize the class
variables. (ii) According to the concept of Object Oriented
(a) i and iii (b) ii and iv Programming, objects are also called as
instances of a class or class variable.
(c) iii, iv and ii (d) ii and iii

co
 [Ans. (d) ii and iii] (iii) In Python, everything is an object. For
example, all integer variables that we use
Very Short Answers 2 MARKS in our program is an object of class int.
1. Write the general form of declaring class in Similarly all string variables are also object

s.
Python. of class string.
Ans. In Python, a class is defined by using the keyword 2. Write a note on self argument used in python
class. Every class has a unique name followed by class function.
a colon ( : ).

ok
Ans. (i) Python class function or Method is very
Syntax :
class class_name: similar to ordinary function with a small
difference that, the class method must have
statement_1
the first argument named as self.
statement_2
o
………….. (ii) No need to pass a value for this argument
………….. when we call the method. Python provides
statement_n its value automatically.
ab

2. Write the syntax for the following (iii) Even if a method takes no arguments, it
(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
ur

(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. 3. Write a python program to find total and
Ans. Python class function or method is very similar
.s

average marks using class.


to ordinary function with a small difference.
The class method must have the first argument Ans. class Student:
named as self. mark1, mark2, mark3 = 45, 91, 71
w

4. Name the function which acts as a constructor #class variable


and destructor.
def process(self): #class method
Ans. Constructor -(- - init - - ( ))
w

Destructor -(- - del - - ( )) sum = Student.mark1 + Student.mark2 +


Student.mark3
5. Write a program in python that illustrate the
use of constructor. avg = sum/3
w

Ans. Program to illustrate Constructor : print("Total Marks = ", sum)


class Sample:
print("Average Marks = ", avg)
def __init__(self, num):
print("Constructor of class Sample...") return
self.num=num S=Student()
print("The value is :", num) S.process()
S=Sample(10)
143
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. Explain the working of the following program. 1. What does sample denotes?
Unit III - Chapter 10

class Sample: 2. What does x, y denotes?


def __init__(self, num): 3. What does s denotes?
print("Constructor of class Ans. 1. It denotes class name
Sample...") 2. x, y is a class variables of the class
self.num=num 3. S is an object created to access the members

m
print("The value is :", num) of the class
S=Sample(10) Long Answers 5 MARKS
Ans. (i) The above class “Sample”, has only a 1. Write a program to check and print if the given

co
constructor with one argument named as number is negative or positive using class.
num. When the constructor gets executed, Ans. class test:
first the print statement, prints the def check (self, num)
“Constructor of class Sample….”, then, the if num> 0:
passing value to the constructor is assigned

s.
print (num, “is positive number”)
to self.num and finally it prints the value else:
passed along with the given string. print (num, “is negative number”)
(ii) The above constructor gets executed n = test ()

ok
automatically, when an object S is created x = int (input(“Enter the number”))
with actual parameter 10. Thus, the Python n. check (x)
displays the following output. 2. Write a menu driven program that keeps
(iii) Constructor of class Sample... record of books available in you school library.
Ans. class Library:
o
The value is : 10
Class variable defined within constructor def __init__(self):
keep count of number of objects created self.bookname=""
ab

with the class. self.author=""


def getdata(self):
5. Fill up the blanks in the following program to self.bookname = input("Enter Name
get the output :  of the Book: ")
Value of x = 10 self.author = input("Enter Author of
ur

Value of y = 20  the Book: ")


Sum of x and y = 30 def display(self):
print("Name of the Book: ",self.bookname)
Class sample:
print("Author of the Book: ",self.author)
.s

x, ____ = 10, 20 ------------------- print(“\n”)


s = ______ ------------------------- book=[] #empty list
print (“value of x =”, _____) ------------- ch = 'y'
print (“value of y =”, _____) ------------- while(ch=='y'):
w

print (“sum of x and y =”, _____) -------- print("1. Add New Book \n 2.Display
Ans. 1. – y Books")
2. – sample () resp = int(input("Enter your choice : "))
w

3. – s. x if(resp==1):
L=Library()
4. – s. y
L.getdata()
5. – s. x + s. y
w

book.append(L)
6. Read the following program. Answer the elif(resp==2):
following question. for x in book:
Class sample: x.display()
x, y = 10, 20 else:
s = sample () print("Invalid input....")
print (s. x + s. y) ch = input("Do you want continue....")

144
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Write a program to store product and its cost def print_bill(self):
price. Display all the available products and

Python Classes and Objects


prompt to enter quantity of all the products. total_price = 0
Finally generate a bill which displays the total for x in range(self.p):
amount to be paid.
q=int(input("Enter the quantify for
Ans. class MyStore:

m
 the product code %d : "%self.__
__prod_code=[]
__prod_name=[] prod_code[x]))
__cost_price=[] self.__prod_quant.append(q)

co
__prod_quant=[]
total_price = total_price +self.__cost_
def getdata(self):
self.p = int(input("Enter no. of products price[x]*self.__prod_quant[x]
 you need to store: "))
print(" Invoice Receipt ")

s.
for x in range(self.p):
self.__prod_code. print("-------------------------------------")
 append(int(input("Enter Product Code: "))) print("Product Code\t Product Name\t

ok
self.__prod_name.append(str(input("Enter  Cost Price\t Quantity \t Total Amount")
 Product Name: ")))
print("-------------------------------------")
self.__cost_price.append(int(input("Enter
 Cost price: "))) for x in range(self.p):
def display(self):
o
print(self.__prod_code[x], "\t\t", self.__
print("Stock in Stores")
 prod_name[x], "\t\t",
print("-------------------------------------")
ab

print("Product Code \t Product Name \t self.__cost_price[x], "\t\t", self.__


 Cost Price")  prod_quant[x], "\t\t",
print("-------------------------------------") self.__prod_quant[x]*self.__cost_
for x in range(self.p): price[x])
ur

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


 prod_name[x], "\t\t", self.__cost_ print("-------------------------------------")
price[x]) print(" Total Amount = ", total_price)
.s

print("-------------------------------------")
w


w
w

145
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

 
UNIT-IV DATABASE CONCEPTS AND MYSQL

m
Chapter
DATABASE CONCEPTS
11

co
s.
CHAPTER SNAPSHOT
11.1 Data
11.2 Information

ok
11.3 Database
11.4 DataBase Management System (DBMS)
11.4.1 Characteristics of Database Management System
11.4.2 Advantages of DBMS
o
11.4.3 Components of DBMS
ab

11.5 Database Structure


11.6 Data Model
11.6.1 Types of Data Model
11.6.2 Types of DBMS Users
ur

11.7 Difference between DBMS and RDBMS


11.8 Types of Relationships
11.9 Relational Algebra in DBMS
.s
w
w
w

[146]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science

Evaluation 9. A tuple is also known as


(a) table (b) row
[PTA-6]

Database Concepts
(c) attribute (d) field
Part - I  [Ans. (b) row]
Choose the best answer  (1 mark) 10. Who developed ER model?

m
1. What is the acronym of DBMS? (a) Chen (b) EF Codd
(a) DataBase Management Symbol (c) Chend (d) Chand
(b) Database Managing System  [Ans. (a) Chen]

co
(c) DataBase Management System Part - II
(d) DataBasic Management System Answer the following questions
 [Ans. (c) DataBase Management System]
 (2 marks)
2. A table is known as
1. Mention few examples of a database.

s.
(a) tuple (b) attribute
(c) relation (d) entity Ans. (i) Foxpro
 [Ans. (c) relation] (ii) DBase
(iii) ADABAS

ok
3. Which database model represents parent-
(iv) Microsoft Excel
child relationship?
(v) Microsoft Square
(a) Relational (b) Network
(vi) Oracle RDBMS
(c) Hierarchical (d) Object
 [Ans. (c) Hierarchical] (vii) My SQL
o
4. Relational database model was first proposed 2. List some examples of RDBMS.
by [HY-2019] Ans. (i) IBM DBZ
ab

(a) E F Codd (b) E E Codd (ii) Maria DB


(c) E F Cadd (d) E F Codder (iii) Microsoft Jet Database Engine
 [Ans. (a) E F Codd ] (iv) My SQL
5. What type of relationship does hierarchical (v) Oracle
ur

model represents? (vi) SQLite


(a) one-to-one (b) one-to-many 3. What is data consistency?
(c) many-to-one (d) many-to-many Ans. Data Consistency means that data values are the
 [Ans. (b) one-to-many]
.s

same at all instances of a database


6. Who is called Father of Relational Database 4. What is the difference between Hierarchical
from the following? and Network data model?
w

(a) Chris Date (b) Hugh Darween Ans.


(c) Edgar Frank Codd
Hierarchical data
(d) Edgar Frank Cadd Network data model
model
[Ans. (c) Edgar Frank Codd]
w


In hierarchical model, a In a Network model, a
7. Which of the following is an RDBMS? child record has only one child may have many
(a) Dbase (b) Foxpro
parent node parent nodes.
w

(c) Microsoft Access (d) SQLite


 [Ans. (d) SQLite] It represents one-to- It represents the data
one relationship called in many-to-many
8. What symbol is used for SELECT statement?
parent-child relationship relationships.
 [PTA-2]
in the form of tree
(a) σ (b) Π (c) X (d) Ω
 [Ans. (a) σ] structure.

147
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5. What is normalization? Table A Table B Table A × Table B
Unit IV - Chapter 11

Ans. Database normalization is the process of 1 S 1 S


structuring a relational database in accordance 2 1 R
with a series of so-called normal forms in order R
2 S
to reduce data redundancy and improve data 3

m
integrity. Table A = 3
2 R

Part - III Table B = 2 3 S


Answer the following questions Table A × B = 3 × 2 = 6
3 R

co
 (3 marks) Cartesian Product

1. What is the difference between Select and 4. Explain Object Model with example. [QY-2019]
Project command? [PTA-2; QY-2019] Ans. Object Model : Object model stores the data
Ans. in the form of objects, attributes and methods,

s.
classes and inheritance. This model handles
Select Project more complex applications, such as Geographic
The SELECT operation The projection method information System (GIS), scientific experiments,
engineering design and manufacturing. It is

ok
is used for selecting defines a relation that used in file Management System. It represents
a subset with tuples contains a vertical subset real world objects, attributes and behaviors. It
according to a given a relation. provides a clear modular structure. It is easy to
condition C. maintain and modify the existing code.
o
Select filters out all tuples The projection Shape
get_area()
that do not satisfy C. eliminates all attributes get_perimeter()
ab

of the input relation but


those mentioned in the
projection list. Circle
Rectangle Triangle
Length Base
Symbol : σ Symbol : π Radius
breath Height
ur

Object Model
2. What is the role of DBA? An example of the Object model is Shape,
Ans. Database Administrator or DBA is the one who Circle, Rectangle and Triangle are all objects
manages the complete database management in this model.
.s

(i) Circle has the attribute radius.


system. DBA takes care of the security of the
(ii)  Rectangle has the attributes length and
DBMS, managing the license keys, managing
breadth.
user accounts and access etc.
w

(iii) Triangle has the attributes base and height.


3. Explain Cartesian Product with a suitable (iv) The objects Circle, Rectangle and Triangle
example. [Govt. MQP-2019; PTA-5] inherit from the object Shape.
w

Ans. (i) Cross product is a way of combining two 5. Write a note on different types of DBMS users.
relations. The resulting relation contains, Ans. Types of DBMS Users
both relations being combined. (i) Database Administrators : Database
w

Administrator or DBA is the one


(ii) A × B means A times B, where the relation
who manages the complete database
A and B have different attributes. management system. DBA takes care of the
(iii) This type of operation is helpful to merge security of the DBMS, managing the license
columns from two relations. keys, managing user accounts and access
etc.

148
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(ii) Application Programmers or Software (ii) 
The basic structure of data in relational
Developers : This user group is involved model is tables (relations). All the

Database Concepts
in developing and designing the parts of information’s related to a particular type is
DBMS. stored in rows of that table.
(iii) End User : End users are the one who (iii) Hence tables are also known as relations
store, retrieve, update and delete data.

m
in a relational model. A relation key is
(iv) Database designers : They are responsible an attribute which uniquely identifies a
for identifying the data to be stored in particular tuple (row in a relation (table)).
the database for choosing appropriate

co
Stu_id Name Age Subj_id Name Teacher
structures to represent and store the data. 1 Malar 17 1 C++ Kannan

Part - IV 2
3
Suncar
Velu
16
16
2
3
Php
Python
Ramakrishnan
Vidhya

Answer the following questions


 (5 marks)

s.
Stu_id Subj_id Marks
1. Explain the different types of data model. 1 1 92
1 2 89
 [HY-2019] 3 2 96

ok
Ans. The different types of a Data Model: Relational Model
Hierarchical Model, Relational Model, Network Network Model : Network database model is
Database Model, Entity Relationship Model, an extended form of hierarchical data model.
Object Model. The difference between hierarchical and
o
Hierarchical Model : Network data model is :
(i)  In hierarchical model, a child record has
(i) Hierarchical model was developed by IBM
only one parent node,
ab

as Information Management System. In


(ii) In a Network model, a child may have
Hierarchical model, data is represented as
many parent nodes. It represents the data
a simple tree like structure form.
in many-to-many relationships.
(ii) This model represents a one-to-many
(iii) 
This model is easier and faster to access the
relationship i.e., parent-child relationship.
ur

data.
One child can have only one parent but one
parent can have many children. School
(iii) This model is mainly used in IBM Main
Frame computers.
.s

This child has


Library Office Staff Room one parent node
School
w

Student Student has 3 parent node


Course Resource
Network Model
(iv) School represents the parent node
w

(v) Library, Office and Staff room is a child to


Theory Lab
school (parent node)
Hierarchical Model (vi) Student is a child to library, office and staff
w

Relational Model : room (one to many relationship)


(i) The Relational Database model was first Entity Relationship Model. (ER model) :
proposed by E.F. Codd in 1970 . Nowadays, (i) 
In this database model, relationship are
it is the most widespread data model used created by dividing the object into entity
for database applications around the world. and its characteristics into attributes.

149
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(ii) 
It was developed by Chen in 1976. This 2. Explain the different types of relationship
Unit IV - Chapter 11

model is useful in developing a conceptual mapping. [PTA-1, 4]


design for the database. It is very simple Ans. The types of relationships used in a database.
and easy to design logical view of data. The (i) One-to-One Relationship
developer can easily understand the system
(ii) One-to-Many Relationship
by looking at ER model constructed.

m
(iii) Many-to-One Relationship
(iii) 
Rectangle represents the entities. E.g.
Doctor and Patient. (iv) Many-to-Many Relationship
(i) One-to-One Relationship : In One-to-

co
(iv) Ellipse represents the attributes E.g. D-id,
D-name, P-id, P-name. Attributes describes One Relationship, one entity is related with
the characteristics and each entity only one other entity. One row in a table is
becomes a major part of the data stored linked with only one row in another table
in the database. Diamond represents the and vice versa.

s.
relationship in ER diagrams For example : A student can have only
E.g. Doctor diagnosis the Patient one exam number
Student Exam No

ok
Doctor Diagnosis Patient

Tamilselvi 1001

D-id D-Name P-id P-Name Jayapandiyan 1002


o
ER model
Sarojini 1003
Object Model :
ab

(i) Object model stores the data in the form of


objects, attributes and methods, classes and One to one Relationships
Inheritance.
(ii) One-to-Many Relationship : In One-to-
(ii) This model handles more complex Many relationship, one entity is related to
ur

applications, such as Geographic many other entities. One row in a table A


information System (GIS), scientific is linked to many rows in a table B, but one
experiments, engineering design and row in a table B is linked to only one row in
manufacturing. table A.
.s

(iii) It is used in file Management System. It For example: One Department has many
represents real world objects, attributes staff members.
and behaviors. It provides a clear modular
w

Staff
structure. It is easy to maintain and modify
the existing code. Department
Gajalakshmi
w

Shape
get_area() Computer Bindhu
get_perimeter()
Tamil Radha
w

Maths Ramesh

Rectangle Triangle Malaiarasu


Circle
Length Base
Radius
breath Height
One to Many Mapping
Object Model

150
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iii) Many-to-One Relationship : In Many- 3. Differentiate DBMS and RDBMS.
to-One Relationship, many entities can be Ans.

Database Concepts
related with only one in the other entity.
Basis of
For example: A number of staff members DBMS RDBMS
Comparison
working in one Department. Multiple rows
in staff members table is related with only Expansion Database Relational

m
Management DataBase
one row in Department table.
System Management
Staff Department
System

co
Data storage Navigational Relational model
model (in tables). ie
Suganya ie data by data in tables as
Computer linked records row and column
Bala
Data Exhibit Not Present

s.
Maths
Malarmathi
redundancy
Normalization Not RDBMS uses
performed normalization

ok
to reduce
Many to one Relationship redundancy
(iv) Many-to-Many Relationship : A many- Data access Consumes Faster, compared
to-many relationship occurs when multiple more time to DBMS.
records in a table are associated with
o
Keys and Does not use. used to establish
multiple records in another table. indexes relationship.
■ Example 1 : Customers and Product Keys are used in
ab

Customers can purchase various products RDBMS.


and Products can be purchased by many Transaction Inefficient, Efficient and
customers management Error prone secure.
■ Example 2 : Students and Courses and insecure.
ur

A student can register for many Courses Distributed Not supported Supported by
and a Course may include many students Databases RDBMS.
■ Example 3 : Books and Student. Example Dbase, SQL server,
FoxPro. Oracle, mysql,
.s

Many Books in a Library are issued to many MariaDB,


students. SQLite.
Book Student
4. Explain the different operators in Relational
w

algebra with suitable examples.


Ans. Relational Algebra is divided into various groups
Unary Relational Operations :
w

C++ Kalaivani
■ SELECT ( symbol : σ)
■ PROJECT ( symbol : Π)
SQL Manjula  Relational Algebra Operations from Set
w

Theory :
python Sridevi ■ UNION (∪)
■ INTERSECTION (∩)
■ DIFFERENCE (–)
■ CARTESIAN PRODUCT (X)
Many to Many Relationship

151
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


SELECT (symbol : σ) : Table B
Unit IV - Chapter 11

(i) General form σc ( R ) with a relation R and


Studio Name
a condition C on the attributes of R.
(ii) The SELECT operation is used for selecting cs1 Kannan
a subset with tuples according to a given cs2 GowriShakaran
condition.

m
cs3 Lenin
(iii) Select filters out all tuples that do not satisfy
C. Result :
STUDENT :

co
Table A ∪ B
Stu Studio Name
Name Course Year
dio
cs1 Kannan
cs1 Kannan Big Data II
cs2 GowriShankaran
cs2Gowri R language I

s.
cs3 Lenin
Shankar
cs4 Padmaja
cs3 Lenin Big Data I
cs4 Padmaja Python I SET DIFFERENCE ( Symbol : - ) :

ok
Programming (i) The result of A – B, is a relation which
Table A includes all tuples that are in A but not in B.
σcourse = “Big Data” (STUDENT ) : (ii) The attribute name of A has to match with
the attribute name in B.
o
PROJECT (symbol : Π) :
(iii) Example 4 ( using Table B) :
(i) The projection eliminates all attributes of
ab

the input relation but those mentioned in Result :


the projection list. Table A – B
(ii) The projection method defines a relation
cs4 Padmaja
that contains a vertical subset of Relation.
(iii) Example 1 using Table A INTERSECTION (symbol : ∩) A ∩ B :
ur

Π course (STUDENT) (i) Defines a relation consisting of a set of all


Result : tuple that are in both in A and B. However,
Course A and B must be union-compatible.
.s

Big Data (ii) Example 5 (using Table B)


R language Table A ∩B
Python Programming cs1 Kannan
w

UNION (Symbol : ∪) : cs3 Lenin


(i) It includes all tuples that are in tables A PRODUCT OR CARTESIAN PRODUCT

or in B. It also eliminates duplicates. Set A
w

(Symbol : X )
Union Set B would be expressed as A ∪ B
(i) Cross product is a way of combining two
(ii) Example 3
Consider the following tables relations. The resulting relation contains,
w

both relations being combined.


Table A
(ii) A × B means A times B, where the relation
Studio Name
A and B have different attributes.
cs1 Kannan
(iii) This type of operation is helpful to merge
cs2 Lenin columns from two relations.
cs3 Padmaja

152
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Table A Table B Table A × Table B

Database Concepts
1 S 1 S

2 1 R
R

m
3 2 S

2 R
Table A = 3

co
Table B = 2 3 S
Table A × B = 3 × 2 = 6
3 R

s.
Cartesian Product
5. Explain the characteristics of DBMS. [PTA-3, 5]
Ans. Characteristics of Database Management System

Reduced Redundancy
o ok
Data stored into Tables Data is never directly stored into the database. Data is stored into tables, created
inside the database. DBMS also allows to have relationship between tables which
makes the data more meaningful and connected.
In the modern world hard drives are very cheap, but earlier when hard drives
were too expensive, unnecessary repetition of data in database was a big
problem But DBMS follows Normalisation which divides the data in such a way
ab

that repetition is minimum.


Data Consistency On live data, it is being continuously updated and added, maintaining the
consistency of data can become a challenge. But DBMS handles it by itself.
Support Multiple user DBMS allows multiple users to work on it(update, insert, delete data) at the
ur

and Concurrent Access same time and still manages to maintain the data consistency.
Query Language DBMS provides users with a simple query language, using which data can be
easily fetched, inserted, deleted and updated in a database.
.s

Security The DBMS also takes care of the security of data, protecting the data from
unauthorized access. In a typical DBMS, we can create user accounts with
different access permissions, using which we can easily secure our data by
w

restricting user access.


DBMS Supports It allows us to better handle and manage data integrity in real world applications
Transactions where multi-threading is extensively used.
w

PTA Questions and Answers


1 MARK
w

1. A column in database table is known as an : [PTA-1]


(a) Atribute (b) Relation (c) Tuple (d) Data
 [Ans. (b) Relation]
2. Which is the entire collection of related data in one table? [PTA-3]
(a) tuple (b) atribute (c) table (d) software
 [Ans. (c) table]
153
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. What type of relationship does hierarchical 5 MARKS
Unit IV - Chapter 11

model represents? [PTA-4]


1. Explain the components of DBMS. 
(a) one-to-one (b) one-to-many
 [Govt. MQP-2019; PTA-6]
(c) many-to-one (d) many-to-many
Ans. The Database Management System can be
 [Ans. (b) one-to-many] divided into five major components as follows:

m
2 MARKS (i) Hardware
1. What are the shapes to represent database (ii) Software
structure in ER model? (iii) Data

co
(or) (iv) Procedures / Methods
Describe the database structure. [PTA-2, 6] (v) Database Access Languages
Ans. (i) Table is the entire collection of related data
in one table, referred to as a File or Table

s.
where the data is organized as row and
column.
Hardware
(ii) Each row in a table represents a record,

ok
which is a set of data for each database
entry.
(iii) Each table column represents a Field, which
groups each piece or item of data among Data Base Procedures
the records into specific categories or types Access / Methods
o
DATA
of data. Eg. StuNo., StuName, StuAge, Languages
StuClass, StuSec.
ab

USER
■ A Table is known as a RELATION Components of DBMS
■ A Row is known as a TUPLE
(i) Hardware : The computer, hard disk, I/O
■ A column is known as an ATTRIBUTE channels for data, and any other physical
component involved in storage of data
ur

2. What are the advantages of DBMS. [PTA-3]


(ii) Software : This main component is a
Ans. Advantages of DBMS :
program that controls everything. The
(i) Segregation of application program DBMS software is capable of understanding
(ii) Minimal data duplication or Data the Database Access Languages and
.s

Redundancy interprets into database commands for


(iii) 
Easy retrieval of data using the Query execution.
Language (iii) Data : It is that resource for which DBMS
w

(iv) Reduced development time and is designed. DBMS creation is to store and
maintenance utilize data.
(iv) Procedures/Methods : They are general
3 MARKS
w

instructions to use a database management


1. Writea short note on Unary Relational system such as installation of DBMS,
Operations of DBMS. [PTA-4] manage databases to take backups, report
w

Ans. A unary operator is an operator that operates


generation, etc.
on only one operant. An operator is referred to (v)  DataBase Access Languages : They are
as binary if it operates on two operands. the languages used to write commands to
access, insert, update and delete data stored
Unary Relational Operations
in any database.
SELECT (Symbol : σ)  Examples of popular DBMS : Dbase,
PROJECT (Symbol : π) FoxPro

154
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. In which of the following data organized in a
Government Exam Questions and Answers
way that, it can be easily accessed, managed

Database Concepts
and updated?
1 MARK
(a) Database (b) DBMS
1. The data model developed by IBM is (c) Structure (d) Object
 [Govt. MQP-2019]  [Ans. (a) Database]

m
(a) Hierarchical (b) Relational
(c) Network (d) ER 5. Which of the following can be a software or
[Ans. (a) Hierarchical] hardware based, with one sole purpose of

co
storiing data?
2. Which model database created by dividing the
object into entity and its Characteristics into (a) DBMS (b) Database
attributes? [QY-2019] (c) Object (d) SQL
(a) Hierarchical (b) Relational  [Ans. (b) Database]
(c) Network (d) E R d a t a b a s e

s.
 [Ans. (a) Edata base] 6. Expand DBMS
2 MARKS (a) Database memory system

ok
1. List the types of database Model. [QY-2019] (b) Digital Based Management source
Ans. The different types of a Data Model (c) Database Management system
(i) Hierarchical Model (d) Digital Database Management system
(ii) Relational Model  [Ans. (c) Database Management system]
o
(iii) Network Database Model
7. Which of the following allows users to store,
(iv) Entity Relationship Model process and analyze data easily?
ab

(v) Object Model (a) My SQL


(b) Relational Algebra
additional questions and Answers (c) Datamodels
(d) DBMS [Ans. (d) DBMS]
Choose the Correct Answer 1 MARK
ur

8. Which of the following provided an interface


1. Which of the following is an organized to perform various operations to create a
collection of data?
database, storing and updating data?
(a) Word Processor (b) Spreadsheet
.s

(a) SQL (b) DBA


(c) Programming language
(c) DBMS (d) Algebra
(d) Database  [Ans. (d) Database]
 [Ans. (c) DBMS]
w

2. Which of the following is an organized 9. Which of the following provides protection


collection of data, which can be stared and a and security to the databases?
cersed through computer system
w

(a) My SQL (b) DBMS


(a) Database (b) Worksheet
(c) Oracel (d) CSV
(c) DBMS (d) Information
 [Ans. (b) DBMS]
w

 [Ans. (a) Database]


10. Which of the following is not an example of
3. Which of the following a data contain? DBMS?
(a) Character (b) text (a) Foxpro (b) Dbase
(c) Word (d) Number (c) CoBoL (d) Ms-Access
(e) All of these [Ans. (c) Word]  [Ans. (c) CoBoL]

155
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


11. Which of the following makes the data more 19. Each row in a table represents a
Unit IV - Chapter 11

meaningful and connected in the database? (a) Fields (b) Record


(a) Information (b) Security (c) Data (d) File
(c) Relationship (d) D a t a m o d e l s  [Ans. (b) Record]
 [Ans. (c) Relationship]
20. Which of the following in a table represents a

m
12. Which of the following divides the data in record?
such a way that repetition of data is minimum
(a) Row (b) Column
in the database?
(c) File (d) Data

co
(a) Segregation (b) Normalisation  [Ans. (a) Row]
(c) Integrity (d) Consistency
21. Which of the following in a table represents a
 [Ans. (b) Normalisation] column?
13. Which of the following characteristics of (a) row (b) column

s.
DBMS become a challenge? (c) data (d) files
(a) Data redundancy (b) Data security  [Ans. (b) column]
(c) Data consistency (d) Data integrity

ok
 [Ans. (c) Data consistency] 22. Which of the following groups data among
records specific categories or types of data?
14. How many major components are there in
(a) Table (b) file
DBMS?
(c) Field (d) Relation
(a) 5 (b) 4 (c) 3 (d) 2
 [Ans. (c) Field]
o
 [Ans. (a) 5]
15. Which of the following is not a DBMS 23. How the data can be represented and accessed
ab

component? from a software after complete implementation


described by
(a) Hardware/Square (b) Data
(a) Data model
(c) Procedures (d) Data model
(b) Data implementation
 [Ans. (d) Data model]
(c) Data redundancy (d) Data integrity
ur

16. Which of the following DBMS components


 [Ans. (a) Data model]
controls everything in a database?
(a) Hardware (b) Square 24. Which of the following is a simple abstraction
(c) Methods (d) Procedures of complex real world data gathering
.s

 [Ans. (b) Square] environment?


(a) Data redundancy (b) Data consistency
17. Which of the following DBMS components
that manage databases to take backups, report (c) Data abstraction (d) Data model
w

generation?  [Ans. (d) Data model]


(a) Square (b) Hardware 25. How many types of data models are there?
(c) Data (d) Procedures (a)
4 (b) 3 (c) 5 (d) 7
w

 [Ans. (d) Procedures]  [Ans. (c) 5]


18. Which of the following used to write 26. Which of the following is not a type of data
commands to update and delete data stored in model?
w

database? (a) Hierarchical model


(a) Procedures (b) Methods (b) Entity Relationship model
(c) Database Access language (c) Object model
(d) Hardware/software (d) Redundancey model
 [Ans. (c) Database Access language]  [Ans. (d) Redundancey model]

156
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


27. Which of the following model was developed 35. Network database model represents the data
by IBM? in which of the relationships?

Database Concepts
(a) ER model (a) one to one (b) one to many
(b) Hierarchical model (c) many to many (d) many to one
(c) Network database model  [Ans. (c) many to many]

m
(d) Object model
36. Which data model is easier and faster in
 [Ans. (b) Hierarchical model] accessing the data?
28. IBM developed Hierarchical model as (a) Relational (b) Network

co
(a) Data Management system (c) ER-mode (d) a l l t h e a b o v e
(b) Information Hierarchical system  [Ans. (b) Network]
(c) Information Management system 37. ER-model was developed in the year
(d) Information model system (a) 1970 (b) 1974
 [Ans. (c) Information Management system]

s.
(c) 1976 (d) 1978
29. In which data model, data is represented as a  [Ans. (c) 1976]
simple tree like structure form?
38. Which of the following database model is

ok
(a) Hierarchical model
useful in developing a conceptual design for
(b) Network database (c) ER model the database?
(d) Relational model (a) Hierarchical (b) Object
 [Ans. (a) Hierarchical model] (c) Relational (d) ER model
30. Which of the following data model is mainly
o
 [Ans. (d) ER model]
used in IBM main frame computers?
(a) ER model (b) Hierarchical 39. Which database model is simple and easy to
ab

(c) Object (d) Relational design logical view of data?


 [Ans. (b) Hierarchical] (a) Hierarchical (b) ER-model
(c) Network (d) Object
31. In which year Relational Database model was  [Ans. (b) ER-model]
first purposed?
ur

(a) 1960 (b) 1964 40. Which of the following data model stores the
(c) 1974 (d) 1970 data in the form of attributes and methods?
 [Ans. (d) 1970] (a) Relational (b) Object
.s

32. The basic structure of data in relational model (c) ER - model (d) All of these
is  [Ans. (d) All of these]
(a) Tables (b) rows
w

41. Object model stores the data in the form of


(c) columns (d) tuples
 [Ans. (a) Tables] (a) objects
(b) attributes and methods
33. Which of the following is the most data model
w

used for data base appreciation? (c) classes and inheritance


(a) ER-Model (b) Hierarchical (d) all of these [Ans. (d) all of these]
(c) Relational (d) table
w

42. GIS expansion is


 [Ans. (c) Relational] (a) Geographic Information System
34. Which of the following data base model is an (b) Global Information System
extended form of hierarchical data model?
(c) Global Information Source
(a) ER-model (b) Network
(d) Geographic Intelligent System
(c) Object (d) Relational
 [Ans. (a) Geographic Information System]
 [Ans. (b) Network]

157
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


43. Which of the following data model handles 51. Which of the following is not a RDBMS
Unit IV - Chapter 11

Geographic Information System? software?


(a) Object (b) ER model (a) Oracle (b) My SQL
(c) Relational (d) None of these (c) Maria DB (d) Foxpro
 [Ans. (a) Object]  [Ans. (d) Foxpro]

m
44. Which data model used in file management 52. Find the odd man out
system? (a) SQLite (b) Maria DB
(a) ER model (b) Relational (c) Oracle (d) Dbase

co
(c) Hierarchical (d) None of these  [Ans. (d) Dbase]
 [Ans. (d) None of these] 53. Find the odd man out
45. How many types of DBMS users are there? (a) ER mode (b) data model
(a)
2 (b) 3 (c) 4 (d) 5 (c) Hierarchical model (d) Relational model

s.
 [Ans. (c) 4]  [Ans. (b) data model]
46. DBA expansion is 54. Database normalization was first proposed by
(a) Data Base Analyst (a) Chen (b) Edgar F Cadd

ok
(b) Data Base Administrators (c) Edgar IF Codd (d) Hugh Darwen
(c) Digital Bound Administrations  [Ans. (c) Edgar IF Codd]
(d) Database Analyser 55. The rule ''reduce data redundancy and improve
 [Ans. (b) Data Base Administrators] data integrity" is known as
o
47. Who takes care of the security of DBMS? (a) Chen rule (b) E F Codd rule
(a) DBA (b) end user
ab

(c) Edgar rule (d) Edgar Frank rule


(c) Software developer (d) DB designer  [Ans. (b) E F Codd rule]
 [Ans. (a) DBA]
56. How many types of relationships used in a
48. Who manages the complete database database?
management system?
ur

(a) 3 (b) 5 (c) 2 (d) 4


(a) End user (b) DBA
 [Ans. (d) 4]
(c) DB designer
(d) Software developer [Ans. (b) DBA] 57. One classroom has many students is an
example of a relationships
.s

49. Who are the one responsible for identifying (a) one to one (b) one to many
the data to be stored in the data base? (c) many to one (d) many to many
(a) DBA  [Ans. (b) one to many]
w

(b) Application programmers


58. Which of the following was used for modeling
(c) End user the data stored in relational databases?
(d) Database designers
w

(a) ER model (b) Modern algebra


 [Ans. (d) Database designers] (c) Relational Algebra (d) Object model
50. RDBMS expansion is  [Ans. (c) Relational Algebra]
w

(a) Redundancy Database Management System 59. Relational Algebra is used to query the
(b) Reliable Database Management System database tables using
(c) Relational Database Management System (a) Dbase (b) SQL
(d) Relational Database Mobile System (c) ER-Model (d) Relational model
 [Ans. (c) Relational Database Management  [Ans. (b) SQL]
System]

158
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


60. Expansion of SQL is Match the following
(a) Structured Question Language

Database Concepts
1. i) Hardware 1) It is a resource for
(b) Selection Query Language
which DBMS is
(c) Structured Query Language designed
(d) Structured Query Language
ii) Square 2) Used to write

m
 [Ans. (d) Structured Query Language] commands
61. Which of the following represents Unary iii) Data 3) Physical
relational operations SELECT components

co
(a) π (b) σ (c) X (d) ∩ involved in data
 [Ans. (b) σ] storage
62. The symbol represents Unary relation iv) Procedures a 4) Manage databases
operation PROJECT is to take backups.
(a) ∩ (b) ∪ (c) σ (d) π

s.
v) Database 5) A program that
 [Ans. (d) π] Access controls everything
63. Find the odd man out language
(a) – (b) X (c) + (d) ∩

ok
(a) 3, 5, 1, 4, 2 (b) 5, 3, 1, 4, 2
 [Ans. (c) +] (c) 3, 5, 4, 1, 2 (d) 3, 5, 1, 2, 4
64. Which operation is used for selecting a subset  [Ans. (a) 3, 5, 1, 4, 2]
with tuples according to a given condition? Choose and fill in the blanks
o
(a) select (b) project 1. The term ________ is used to refer to any of
(c) product (d) union the DBMS
 [Ans. (a) select]
ab

(a) Object (b) Database


65. Which of the following defines a relation that (c) Data model (d) Data mining
contains a vertical subset of relation?  [Ans. (b) Database]
(a) select (b) product 2. ______ is formatted data
(c) intersection (d) project
ur

(a) Raw facts (b) Database


 [Ans. (d) project] (c) Information (d) DBMS
66. Which of the following removes the duplicate  [Ans. (c) Information]
rows in database? 3. When the data is processed It gives a
.s

(a) SELECT (b) PROJECT meaningful __________


(c) PRODUCT (d) INTERSECTION (a) Database (b) Information
 [Ans. (b) PROJECT] (c) Facts (d) Entities
w

 [Ans. (b) Information]


67. Which of the following includes all types that
are in tables A or in B? 4. _________ is a repository collection of related
w

(a) A ∪ B (b) A – B data


(c) A × B (d) A ∩ B (a) SQL (b) Information
 [Ans. (a) A ∪ B] (c) Entities (d) Database
w

 [Ans. (d) Database]


68. Which defines a relation consisting of a set of
all tuple that are in both in A and B? 5. A __________ is a software used to create,
store and manipulate database
(a) A ∪ B (b) A – B
(c) A × B (d) A ∩ B (a) Relational Algebra (b) DBMS
 [Ans. (d) A ∩ B] (c) SQL (d) My SQL
 [Ans. (b) DBMS]

159
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


6. In database, the data stored in _______ 15. Each column in a table represents a______
Unit IV - Chapter 11

(a) Tables (b) Sets (a) Record (b) Data


(c) Lists (d) DBMS (c) Field (d) Method
 [Ans. (a) Tables]  [Ans. (c) Field]
7. In ______ where the data is organized as row 16. ________ database model is an extended form

m
and column of hierarchical data model
(a) Database (b) DBMS (a) object (b) Relational
(c) File or table (c) ER model (d) Network

co
(d) Procedure or methods
 [Ans. (d) Network]
 [Ans. (c) File or table]
8. Hierarchical model represents a ______ 17. _______ data model provides a clear modular
relationship. structure of a data

s.
(a) one to one (b) many to one (a) Object (b) Relational
(c) are to many (d) many to many (c) Hierarchical/ER-model
 [Ans. (c) are to many] (d) All of these [Ans. (a) Object]

ok
9. A table row is known as_______ 18. Doctor and Patient is an example of ______
(a) Relation (b) Attribute database model
(c) field (d) tuple (a) ER-model (b) Relation
 [Ans. (d) tuple] (c) Object (d) Hierarchical
o
10. A table column is known as_________  [Ans. (a) ER-model]
(a) Relation (b) Attribute
19. In _________ data model, the data stores in
ab

(c) Tuple (d) record


the form of classes and inheritance.
 [Ans. (b) Attribute]
(a) Hierarchical
11. _______ are also known as relations in a (b) Entity relationship
relational model
(c) Object (d) Network
ur

(a) Table rows (b) Tables


 [Ans. (c) Object]
(c) Table columns (d) Tuples
 [Ans. (b) Tables] 20. The result of _________ is a relation which
includes all tuples that are in A but not in B.
.s

12. All the information is related to a particular


type is stored in _________ of that table (a) A ∩ B (b) A ∪ B
(a) Columns (b) fields (c) A – B (d) A × B
(c) rows (d) file  [Ans. (c) A – B]
w

 [Ans. (c) rows] 21. _______ is a computer based record keeping


13. A relation key is a key which uniquely identifies system
w

a particular __________ (a) Data model


(a) columns (b) fields (b) Data relationships
(c) tuples (d) none of these (c) DBMS
w

 [Ans. (c) tuples]


(d) Entity relationship [Ans. (c) DBMS]
14. A _______ is an attribute which uniquely
identifies a particular tuple 22. A way of combining two relations is_______
(a) relation key (b) row key (a) A ∪ B (b) A × B
(c) data key (d) tuple key (c) A ∩ B (d) A σ B
 [Ans. (a) relation key] [Ans. (b) A × B]

160
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


23. Relational Algebra was first created by______ 2. (a) U
 sing ER model, it is easy to design logical
(a) E F Codd (b) Chen view of data

Database Concepts
(c) Chris Date (d) Hugh Darwen (b)
Object model handles more complex
 [Ans. (a) E F Codd] applications.

24. _______ are the one who store, retrieve, update (c) ER model is useful in developing a

m
and delete data conceptual design of a database
(a) DBA (d) All the above [Ans. (d) All the above]
(b) Database designers

co
Choose the incorrect statement
(c) Application developers
(d) End user [Ans. (d) End user] 1. (i) DBMS maintains data consistency
(ii) DBMS does not provides protection and
Choose the correct pair
security to the database

s.
1. (a) Table row = tuple (iii) DBMS provides an interface to perform
(b) Table column = Relation creation, storing and updating data in the
(c) Table = Attribute database.

ok
(d) Table = record (iv) DBMS can be a square or hardware based
 [Ans. (a) Table row = Tuple] with one sole purpose of storing data
2. (a) Select - ∩ (a) i and ii (b) only ii
(b) Product - σ (c) iii and iv (d) ii and iv
o
(c) Project - π  [Ans. (d) ii and iv]
(d) Intersection - ∪ [Ans. (c) Project - π]
ab

2. (a) IBM developed Hierarchical data model


Choose the incorrect pair
(b) EF Codd proposed the Relational database
1. (a) Product - ∪
model
(b) Select - σ
(c) Network model represents the data in many-
ur

(c) Project - π
to one relationships
(d) Intersection - ∩ [Ans. (a) Product - ∪]
(d) Chen developed the ER model
2. (a) Table = file
 [Ans. (c) Network model represents the data
.s

(b) Table = Data


 in many-to one relationships]
(c) Table = Relation
(d) Table row = tuple 3. (i) 
End users are the one who manage the
license keys.
w

 [Ans. (b) Table = Data]


(ii) DBA are the one who stores, retrieve, update
Choose the correct statement and delete data.
1. (a) In 1970, Chen developed the ER-model
w

(iii) Choosing appropriate structures to represent


(b) Object model does not store the data in the data and store the data in the database is
form of classes and inheritance. done by database designers.
w

(c) In 1976, EF Codd proposed Relational (iv) Application programmers are involved in
database model developing and designing the parts of DBMs
(d) Data model is a simple abstraction of complex (a) i and ii (b) iii and iv
real world data gathering environment.
(c) i and iii (d) ii and iv
[Ans. (d) Data model is a simple abstraction
of complex real world data gathering [Ans. (a) i and ii]
environment]
161
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. (i) Data redundancy not present in RDBMS (ii) PROJECT Operation (symbol : Π) The
Unit IV - Chapter 11

(ii) DBMS uses normalization to reduce projection eliminates all attributes of the
redundancy input relation but those mentioned in the
(iii)
Distributed Database not supported by projection list. The projection method
RDBMS defines a relation that contains a vertical
subset of Relation.

m
(iv) RDBMS uses keys and indexes to establish
relationship. Short Answers 3 MARKS
(a) i and ii (b) ii and iii 1. What does the term database refers?
(c) iii and iv (d) i and iv Ans. (i) A database is an organized collection

co
 [Ans. (b) ii and iii] of data, generally stored and accessed
Very Short Answers 2 MARKS electronically from a computer system.
(ii) The term "database" is also used to refer to
1. What is database? any of the DBMS, the database system or an

s.
Ans. (i) Database is a repository collection of related application associated with the database.
data organized in a way that data can be (ii) Because of the close relationship between
easily accessed, managed and updated. them, the term "database" is oft en used

ok
(ii) Database can be a soft ware or hardware casually to refer to both a database and the
based, with one sole purpose of storing DBMS used to manipulate it.
data. 2. Write a note on DBMS or write a note on a
2. Differentiate data and information. software that allows us to create, define and
Ans. (i) Data are raw facts stored in a computer. A manipulate database.
o
data may contain any character, text, word Ans. (i) A DBMS is a soft ware that allows us to
or a number. create, define and manipulate database,
ab

(ii) Information is formatted data, which allows allowing users to store, process and analyze
to be utilized in a significant way. data easily.
3. List the characteristics of DBMS. (ii) DBMS provides us with an interface or
a tool, to perform various operations to
Ans. DBMS Supports Transactions : It allows us
create a database, storing of data and for
ur

to better handle and manage data integrity in


updating data, etc.
real world applications where multi-threading is
(iii) DBMS also provides protection and
extensively used.
security to the databases. It also maintains
4. List the types of RDBMS software. data consistency in case of multiple users.
.s

Ans. SQL server, Oracle, MySQL, MariaDB, SQLite.


3. List the components of DBMS.
5. What is E F Codd rules? Ans. The Database Management System can be
Ans. Database normalization was first proposed by divided into five major components as follows:
w

Dr. Edgar F Codd as an integral part of RDBMS (i) Hardware


in order to reduce data redundancy and improve (ii) Software
data integrity. These rules are known as E F (iii) Data
w

Codd Rules. (iv) Procedures / Methods


(v) Database Access Languages
6. Write a note on
4. Fill up the blank.
w

(i) SELECT Operation (i) A table is known as a _________


(ii) PROJECT Operation (ii) A table row is known as a ________
Ans. (i) SELECT Operation (symbol : σ): The (iii) A table column is known as a ________
SELECT operation is used for selecting Ans. (i) Relation
a subset with tuples according to a given (ii) Tuple
condition. (iii) Attribute

162
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5. Identity which is a DBMS and RDBMS 9. Write a short note on the database model, in
software from the following. which relationship are created by dividing the

Database Concepts
(i) SQlite object into entity.
(ii) Foxpro Ans. Entity Relationship Model. (ER model) :
(iii) MySQL (i) In this database model, relationship are

m
(iv) Dbase created by dividing the object into entity
and its characteristics into attributes.
Ans. (i) RDBMS (ii) DBMS
(iii) RDBMS (iv) DBMS (ii) It was developed by Chen in 1976. This

co
model is useful in developing a conceptual
6. Write the importance of using data model. design for the database.
Ans. (i)  A data model describes how the data can be (iii) It is very simple and easy to design logical
represented and accessed from a software
view of data. The developer can easily
after complete implementation

s.
understand the system by looking at ER
(ii)  It is a simple abstraction of complex real
model constructed.
world data gathering environment.
(iii)  The main purpose of data model is to give an 10. List the types of DBMS users.

ok
idea as how the final system or software will Ans. (i) Database Administrators(DBA)
look like after development is completed.
(ii) Application or software developers
7. Write a short note on Relational data model.
Ans. (i) The Relational Database model was first (iii) End User
o
proposed by E.F. Codd in 1970. It is the (iv) Database designers.
most widespread data model used for
11. What is Relational Algebra?
database applications around the world.
ab

(ii) The basic structure of data in relational Ans. (i) Relational Algebra, was first created by
model is tables (relations). All the Edgar F Codd while at IBM. It was used
information’s related to a particular type is for modeling the data stored in relational
stored in rows of that table. databases and defining queries on it.
ur

(iii) Hence tables are also known as relations (ii) Relational Algebra is a procedural query
in a relational model. A relation key is language used to query the database tables
an attribute which uniquely identifies a using SQL.
particular tuple (row in a relation (table)).
(iii) Relational algebra operations are performed
.s

8. Explain the data model that represent parent recursively on a relation (table) to yield an
child relationship. output. The output of these operations is
Ans. (i) Hierarchical model was developed by IBM a new relation, which might be formed by
w

as Information Management System. one or more input relations.


(ii) In Hierarchical model, data is represented 12. Write the symbol used for the following.
as a simple tree like structure form.
(i) SELECT (ii) PROJECT
w

This model represents a one-to-many


relationship ie parent-child relationship. (iii) Union (iv) Intersection
(iii) One child can have only one parent but (v) Difference (vi) PRODUCT
one parent can have many children. This
w

Ans. (i) σ (ii) π (iii) ∪


model is mainly used in IBM Main Frame
computers. (iv) ∩ (v) – (vi) X



163
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

QUERY
STRUCTURED
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

  
Chapter

12 LANGUAGE (SQL)

m

co
s.
CHAPTER SNAPSHOT
12.1 Introduction to SQL

ok
12.2 Role of SQL in RDBMS
12.3 Processing Skills of SQL
12.4 Creating Database
12.5 Components of SQL
12.5.1. Data Definition Language
o
12.5.2. Data Manipulation Language
12.5.3. Data Control Language
ab

12.5.4. Transactional Control Language


12.5.5. Data Query Language
12.6 Data Types
12.7 SQL Commands and their Functions
ur

12.7.1. DDL Commands


12.7.2. Type of Constraints
12.7.3. DML Commands
.s

12.7.4. Some Additional DDL Commands


12.7.5. DQL Command - Select Command
12.7.6. TCL Commands
w
w
w

[164]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science

Evaluation 2. Differentiate
constraint.
Unique and Primary Key
[PTA-6]

Structured Query Language


Ans.
Part - I
Unique Key Primary Key
Choose the best answer (1 mark) Constraint Constraint

m
(i) The constraint This constraint declares
1. Which commands provide definitions for
ensures that no a field as a Primary Key
creating table structure, deleting relations,
two rows have which helps to uniquely
and modifying relation schemas. the same value

co
(a) DDL (b) DML identify a record.
in the specified
(c) DCL (d) DQL columns.
 [Ans. (a) DDL] (ii) The UNIQUE The Primary Key does
constraint can be not allow NULL values
2. Which command lets to change the structure

s.
applied only to and therefore a field
of the table? fields that have declared as Primary
(a) SELECT (b) ORDER BY also been declared Key must have the NOT
as NOT NULL. NULL constraint.

ok
(c) MODIFY (d) ALTER
 [Ans. (d) ALTER] 3. Write the difference between table constraint
and column constraint?
3. The command to delete a table is
Ans.
(a) DROP (b) DELETE
Column constraint Table constraint
o
(c) DELETE ALL (d) ALTER TABLE
Column constraint can be Table constraint is
 [Ans. (a) DROP]
ab

applied only to individual applied to a group of


4. Queries can be generated using column. one or more column.
(a) SELECT (b) ORDER BY
4. Which component of SQL lets insert values in
(c) MODIFY (d) ALTER tables and which lets to create a table?
 [Ans. (a) SELECT]
ur

Ans.
5. The clause used to sort data in a database Command Description Component
 [HY-2019] Insert Inserts data into a DML
(a) SORT BY (b) ORDER BY table
.s

(c) GROUP BY (d) SELECT Create To create tables in the DDL


database
 [Ans. (b) ORDER BY]
w

5. What is the difference between SQL and


Part - II MySQL? [PTA-5]
Ans.
Answer the following questions
w

SQL MySQL
 (2 marks) Structured Query Language MySQL is a database
is a Language used for management system,
1. Write a query that selects all students whose
w

accessing databases. like SQL Server,


age is less than 18 in order wise. Oracle, Informix,
Ans. Query : SELECT * FROM student WHERE Age < = Postgres, etc.
18 ORDER BY Name; SQL is a DBMS MySQL is a RDBMS

165
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Part - III (ii) The different states of our table can be
Answer the following questions saved at anytime using different names and
Unit IV - Chapter 12

the rollback to that state can be done using


 (3 marks)
the ROLLBACK command.
1. What is a constraint? Write short note on (iii) Example :
Primary key constraint. [HY-2019]

m
SAVEPOINT savepoint_name;
Ans. Constraints are used to limit the type of data that
can go into a table. This ensures the accuracy and UPDATE Student SET Name = ‘Mini’
reliability of the data in the database. Constraints  WHERE Admno=105;

co
could be either on a column level or a table level. SAVEPOINT A;
Constraint is a condition applicable on a field or
5. Write a SQL statement using DISTINCT
set of fields.
keyword.
Primary Constraint :
Ans. (i) The DISTINCT keyword is used along
(i) This constraint declares a field as a Primary

s.
with the SELECT command to eliminate
key which helps to uniquely identify a
record. duplicate rows in the table. This helps to
eliminate redundant data.
(ii) It is similar to unique constraint except

ok
that only one field of a table can be set as (ii) For Example: SELECT DISTINCT Place
primary key. FROM Student;
(iii) 
The primary key does not allow NULL Part - IV
values and therefore a field declared as Answer the following questions
o
primary key must have the NOT NULL
constraint.  (5 marks)
ab

2. Write a SQL statement to modify the student


1. Write the different types of constraints and
table structure by adding a new field.
their functions. [PTA-3]
Ans. ALTER TABLE <table-name> ADD <column-
name><data type><size>; Ans. Type of Constraints : Constraints ensure
database integrity, therefore known as database
ur

3. Write any three DDL commands. [PTA-2]


integrity constraints. The different type of
Ans. Data Definition Language :
constraints are :
(i) Create Command : To create tables in the
database. Unique Constraint
.s

CREATE TABLE Student (Admno integer,


Name char(20), Gender char(1), Age Primary Key Constraint
integer); Constraint
w

(ii) Alter Command : Alters the structure of Default Constraint


the database.
Check Constraint
ALTER TABLE Student ADD Address
w

char; Unique Constraint :


(iii) Drop Command : Delete tables from (i) This constraint ensures that no two rows
database. have the same value in the specified
DROP TABLE Student;
w

columns. For example UNIQUE constraint


4. Write the use of Savepoint command with an applied on Admno of student table ensures
example. that no two students have the same
Ans. (i) The SAVEPOINT command is used to admission number and the constraint can
temporarily save a transaction so that be used as:
you can rollback to the point whenever
required.

166
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(ii) CREATE TABLE Student : Default Constraint :
( (i) The DEFAULT constraint is used to assign

Structured Query Language


Admno integer NOT NULL UNIQUE, → a default value for the field. When no
 Unique constraint value is given for the specified field having
Name char (20) NOT NULL, DEFAULT constraint, automatically the
Gender char (1), default value will be assigned to the field.

m
Age integer, (ii)  Example showing DEFAULT Constraint
Place char (10), in the student table:
(iii) CREATE TABLE Student :
);
(

co
 e UNIQUE constraint can be applied
(iii) Th Admno integer NOT NULL PRIMARY
only to fields that have also been declared KEY,
as NOT NULL. Name char(20)NOT NULL,
(iv) When two constraints are applied on a single Gender char(1),
Age integer DEFAULT = “17”,

s.
field, it is known as multiple constraints. In
the above Multiple constraints NOT NULL  → Default Constraint
and UNIQUE are applied on a single field Place char(10),
Admno, the constraints are separated by a );

ok
space and at the end of the field definition (iv)  In the above example the “Age” field is
a comma(,) is added. By adding these two assigned a default value of 17, therefore
constraints the field Admno must take when no value is entered in age by the
user, it automatically assigns 17 to Age.
some value ie. will not be NULL and should
Check Constraint :
not be duplicated.
o
(i) This constraint helps to set a limit value
Primary Key Constraint : placed for a field. When we define a check
(i) This constraint declares a field as a Primary constraint on a single column, it allows only
ab

key which helps to uniquely identify a the restricted values on that field. Example
record. It is similar to unique constraint showing check constraint in the student
except that only one field of a table can be table:
set as primary key. (ii) CREATE TABLE Student :
(
ur

(ii) The primary key does not allow NULL


Admno integer NOT NULL PRIMARY
values and therefore a field declared as KEY
primary key must have the NOT NULL Name char(20)NOT NULL,
constraint. Gender char(1),
.s

(iii) Example showing Primary Key Constraint Age integer (CHECK<=19), → Check
in the student table: Constraint
(iv) CREATE TABLE Student : Place char(10),
w

( );
Admno integer NOT NULL PRIMARY (iii) In the above example the check constraint
 KEY, → Primary Key constraint is set to Age field where the value of Age
w

Name char(20)NOT NULL, must be less than or equal to 19.


(iv)  The check constraint may use relational
Gender char(1),
and logical operators for condition.
Age integer, Table Constraint :
w

Place char(10), (i) When the constraint is applied to a group


); of fields of the table, it is known as Table
(v) In the above example the Admno field has constraint. The table constraint is normally
been set as primary key and therefore will given at the end of the table definition.
help us to uniquely identify a record, it is (ii) Let us take a new table namely Student1
also set NOT NULL, therefore this field with the following fields Admno, Firstname,
value cannot be empty. Lastname, Gender, Age, Place:
167
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(iii) CREATE TABLE Student 1 : 3. What are the components of SQL? Write the
( commands in each. [Govt. MQP-2019]
Unit IV - Chapter 12

Admno integer NOT NULL, Ans. Components of SQL : SQL commands are
Firstname char(20), divided into five categories:
Lastname char(20), DDL - Data Definition Language
Gender char(1),

m
Age integer, DML - Data Manipulation Language
Place char(10),
PRIMARY KEY (Firstname, Lastname) → DCL - Data Control Language

co
 Table constraint
); TCL - Transaction Control Language
(iv) In the above example, the two fields,
Firstname and Lastname are defined as DQL - Data Query Language
Primary key which is a Table constraint.

s.
2. Consider the following employee table. Write Data Definition Language :
SQL commands for the qtns.(i) to (v). [PTA-2] (i) The Data Definition Language (DDL)
consist of SQL statements used to define
EMP ALLO

ok
NAME DESIG PAY the database structure or schema.
CODE WANCE (ii) It simply deals with descriptions of the
S1001 Hariharan Supervisor 29000 12000 database schema and is used to create and
P1002 Shaji Operator 10000 5500 modify the structure of database objects in
databases.
P1003 Prasad Operator 12000 6500
o
(iii) SQL commands which comes under Data
C1004 Manjima Clerk 8000 4500 Definition Language are :
M1005 Ratheesh Mechanic 20000 7000
ab

Create To create tables in the database.


(i) T o display the details of all employees in Alter Alters the structure of the
descending order of pay. database.
(ii) To display all employees whose allowance Drop Delete tables from database.
is between 5000 and 7000. Truncate Remove all records from a
ur

(iii) 
To remove the employees who are table, also release the space
mechanic. occupied by those records.
(iv) To add a new row. Data Manipulation Language :
.s

(v) To display the details of all employees (i) A Data Manipulation Language (DML) is
who are operators. a computer programming language used
for adding (inserting), removing (deleting),
Ans. (i) SELECT * FROM Employee ORDER BY
and modifying (updating) data in a
w

PAY DESC; database.


(ii) SELECT * FROM Employee WHERE (ii) In SQL, the data manipulation language
ALLOWANCE BETWEEN 5000 AND comprises the SQL-data change statements,
which modify stored data but not the
w

7000; schema of the database table.


(iii) DELETE FROM Employee WHERE (iii) SQL commands which comes under Data
DESIG='Mechanic'; Manipulation Language are :
w

(iv) INSERT INTO Employee (empcode, name, Insert Inserts data into a table
desig, pay, allowance) VALUES (S1002, Update Updates the existing data
Baskaran, Supervisor, 29000, 12000); within a table.
Delete Deletes all records from a table,
(v) SELECT * FROM Employee WHERE
but not the space occupied by
DESIG='Operator'; them.

168
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Data Control Language : Ans. (i) GROUP BY clause :

Structured Query Language


(i)  A Data Control Language (DCL) is a ■ The GROUP BY clause is used with the
programming language used to control the SELECT statement to group the students
access of data stored in a database. It is used on rows or columns having identical values
for controlling privileges in the database or divide the table in to groups.
(Authorization). ■ For example to know the number of male

m
(ii) The privileges are required for performing students or female students of a class,
all the database operations such as creating the GROUP BY clause may be used. It is
sequences, views of tables etc. mostly used in conjunction with aggregate
functions to produce summary reports

co
(iii) SQL commands which come under Data
Control Language are : from the database.
■ The syntax for the GROUP BY clause is
Grant Grants permission to one or
more users to perform specific ■ SELECT <column-names> FROM <table-
name> GROUP BY <column-name>
tasks.

s.
HAVING condition];
Revoke Withdraws the access ■ To apply the above command on the

permission given by the student table :
GRANT statement.

ok
■ SELECT Gender FROM Student GROUP
Transactional Control Language : BY Gender;
(i)  Transactional control language (TCL) ■ The following command will give the

commands are used to manage transactions below given result :
in the database. These are used to manage
the changes made to the data in a table by Gender
o
DML statements.
(ii) SQL command which come under Transfer M
ab

Control Language are :


F
Commit Saves any transaction into the ■ SELECT Gender, count(*) FROM
database permanently. Student GROUP BY Gender;
Roll Restores the database to last Gender count(*)
ur

back commit state. M 5


Save Temporarily save a F 3
point transaction so that you can (ii) ORDER BY clause :
rollback. ■  e ORDER BY clause in SQL is used
Th
.s

Data query language : to sort the data in either ascending


(i)  The Data Query Language consist of or descending based on one or more
commands used to query or retrieve data columns.
w

from a database. (a) By default ORDER BY sorts the data


in ascending order.
(ii) One such SQL command in Data Query (b) We can use the keyword DESC to sort
Language is the data in descending order and the
w

Select It displays the records keyword ASC to sort in ascending


from the table. order.
■ The ORDER BY clause is used as :
w

4. Construct the following SQL statements in the ■ SELECT<column-name>[,<column-


student table. name>,….] FROM <table-name>ORDER
(i) SELECT statement using GROUP BY BY<column1>,<column2>,…ASC| DESC ;
clause. ■ For example :
(ii) 
SELECT statement using ORDER BY To display the students in alphabetical
order of their names, the command is used
clause. as

169
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


■ SELECT * FROM Student ORDER BY 4. In the above table set the employee number as
Name; primary key and check for NULL values in any
Unit IV - Chapter 12

The above student table is arranged as field.


follows : Ans. CREATE TABLE employee (empno ineger
Admno Name Gender Age Place NOT NULL PRIMARY KEY, ename char(30)
NOT NULL, desig char(30), doj datetime, basic

m
104 Abinandh M 18 Chennai
integer);
101 Adarsh M 18 Delhi 5. Prepare a list of all employees who are
102 Akshith M 17 Bangalore Managers..

co
Ans. SELECT*FROM employee WHERE desig =
100 Ashish M 17 Chennai
'Managers';
103 Ayush M 18 Delhi
PTA Questions and Answers
106 Devika F 19 Bangalore

s.
107 Hema F 17 Chennai 1 MARK
1. Pick odd one : [PTA-1]
105 Revathi F 19 Chennai
(a) Commit (b) Roll back

ok
5. Write a SQL statement to create a table for (c) Save point (d) Revoke
employee having any five fields and create a  [Ans. (d) Revoke]
table constraint for the employee table. 2. Pick Odd one: [PTA-2]
Ans. CREATE TABLE employee (a) INSERT (b) DELETE
o
( (c) UPDATE (d) TRANCATE
empcode integer NOTNULL,  [Ans. (D) TRANCATE]
ab

name char(20), 3. The TCL command used to restores the


desigchar(20), database to the last commit state. [PTA-3]
Pay integer, (a) Commit (b) SavePoint
allowance integer, (c) Insert (d) Rollback
ur

PRIMARY KEY (empno)  [Ans. (d) Rollback]


); 4. The statement in SQL is used to retrieve data
Hands on Experience from a table in a database: [PTA-3]
(a) SELECT (b) CREATE
.s

1. Create a query of the student table in the (c) DISTINCT (d) ORDER BY
following order of field name, age, place and  [Ans. (a) SELECT]
admno. 5. The SQL command 'Truncate' comes under:
w

Ans. CREATE TABLE Student (Name char(30), age  [PTA-4]


integer, place char(30), admno integer)); (a) DDL (b) DML
2. Create a query to display the student table with (c) TCL (d) DQL
w

students of age more than 18 with unique city.  [Ans. (a) DDL]
Ans. SELECT*FROM student WHERE age >= 18 6. Match the following: [PTA-5]
GROUP BY city; (a) DELETE - (i) DDL
w

3. Create a employee table with the following (b) DROP - (ii) DQL
fields employee number, employee name, (c) SELECT - (iii) TCL
designation, data of joining and basic pay. (d) COMMIT - (iv) DML
Ans. CREATE TABLE employee (empNo integer, (a) a-iv, b-iii, c-ii, d-i (b) a-iv, b-i, c-ii, d-iii
ename char(30), desig char(30), doj datetime, (c) a-i, b-iv, c-iii, d-ii (d) a-i, b-iii, c-iv, d-ii
basic integer);  [Ans. (b) a-iv, b-i, c-ii, d-iii]

170
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


7. Pick odd one: [PTA-6] 5 MARKS
(a) CREATE (b) UPDATE

Structured Query Language


1. Explain about the TCL commands with
(c) ALTER (d) DROP suitable examples. [PTA-1]
 [Ans. (B) UPDATE] Ans. TCL commands :
2 MARKS (i) COMMIT command : The COMMIT

m
1. List any four DDL commands. [PTA-1]
command is used to permanently save
any transaction to the database. When
Ans. (i) ALTER (ii) TRUNCATE
any DML commands like INSERT,
(iii) DROP (iv) DELETE

co
UPDATE, DELETE commands are used,
2. Write a Python code to create a database in SQLite. the changes made by these commands are
 [PTA-3]
not permanent. It is marked permanent
Ans. To create a database, type the following
only after the COMMIT command is
command in the prompt:
given from the SQL prompt. Once the

s.
CREATE DATABASE database_name;
For example ; To create a database to store the COMMIT command is given, the changes
tables: made cannot be rolled back. The COMMIT
CREATE DATABASE stud; command is used as COMMIT;

ok
3. What are DCL commands in SQL? [PTA-4] (ii) ROLLBACK command :
Ans. SQL commands which come under Data  The ROLLBACK command restores the
Control Language are: database to the last commited state. It is
(i) Grant : Grants permission to one or more used with SAVEPOINT command to jump
o
users to perform specific tasks. to a particular savepoint location. The
(ii) Revoke : Withdraws the access permission syntax for the ROLLBACK command is :
ab

given by the GRANT statement. ROLL BACK TO save point name;


3 MARKS (iii) SAVEPOINT command :
1. Compare Delete, Truncate and Drop in SQL.  The SAVEPOINT command is used to
(or) temporarily save a transaction so that you
ur

can rollback to the point whenever required.


What is the use of DELETE, TRUNCATE and
The different states of our table can be saved
DROP commands in SQL? [PTA-1, 3]
at anytime using different names and the
Ans. rollback to that state can be done using the
.s

Delete Truncate Drop ROLLBACK command.


The DELETE The The DROP 2. Explain about DML commands of SQL.
command TRUNCATE TABLE
permanently command is  [PTA-4]
w

command is
removes one or used to delete used to remove Ans. DML COMMANDS :
more records all the rows a table from Once the schema or structure of the table is
from the table. from the table, the database created, values can be added to the table. The
w

It removes the once a table DML commands consist of inserting, deleting


the structure
entire row, not is dropped and updating rows into the table.
individual fields remains and we cannot
of the row. so no the space is get it back, (i) INSERT command :
w

field arguments freed from the so be careful The INSERT command helps to add new data to
is needed. table. while using the database or add new records to thetable. The
Syntax : Syntax : DROP TABLE command is used as follows:
DELETE TRUNCATE command.
INSERT INTO <table-name> [column-list]
FROM table- TABLE table- Syntax :
 VALUES (values);
name WHERE name; DROP TABLE
condition; table-name;

171
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


INSERT INTO Student (Admno, Name, Gender,
 Age, Place) Admno Name Gender Age Place
Unit IV - Chapter 12

VALUES (100,’ Ashish’,’ M’, 17,’ Chennai’); 100 Ashish M 17 Chennai


INSERT INTO Student (Admno, Name, Gender,
 Age, Place) 101 Adarsh M 18 Delhi
VALUES (101, ‘Adarsh’, ‘M’, 18, ‘Delhi’); 103 Akshith M 20 Bangalore

m
Two new records are added to the table as shown 104 Ayush M 18 Delhi
below:
To update multiple fields, multiple field
Admno Name Gender Age Place assignment can be specified with the SET

co
100 Ashish M 17 Chennai clause separated by comma. For example to
update multiple fields in the Student table, the
101 Adarsh M 18 Delhi command is given as:
(ii) DELETE COMMAND UPDATE Student SET Age=18, Place =

s.
The DELETE command permanently removes  ‘Chennai’ WHERE Admno = 102;
one or more records from the table. It removes 3. What are the functions performed by DDL.
the entire row, not individual fields of the row,  [PTA-6]
so no field argument is needed. The DELETE

ok
Ans. (i)  It should identify the type of data division
command is used as follows : such as data item, segment, record and
DELETE FROM table-name WHERE condition; database file.
For example to delete the record whose (ii) It gives a unique name to each data item
admission number is 104 the command is given type, record type, file type and data base.
o
as follows: (iii) It should specify the proper data type.
DELETE FROM Student WHERE Admno=104; (iv) It should define the size of the data item.
ab

104 Abinandh M 18 Chennai (v) It may define the range of values that a data
item may use.
The following record is deleted from the Student
(vi) It may specify privacy locks for preventing
table.
unauthorized data entry.
To delete all the rows of the table, the command
ur

is used as : Government Exam Questions and Answers


DELETE * FROM Student;
The table will be empty now and could be 1 MARK
destroyed using the DROP command.
1. Which command saves any transaction in
.s

(iii) UPDATE COMMAND


database permanently? [QY-2019]
The UPDATE command updates some or all
(a) save (b) save point
data values in a database. It can update one or
(c) commit (d) roll back 
w

more records in a table. The UPDATE command


specifies the rows to be changed using the  [Ans. (c) Commit]
WHERE clause and the new data using the SET 2. The original version of SQL is released in the
keyword. The command is used as follows:
w

year _____. [QY-2019]


UPDATE <table-name> SET column-name =
(a) 1970 (b) 1980
 value, column-name = value,…
WHERE condition; (c) 1986 (d) 1992 
w

For example to update the following fields:  [Ans. (a) 1970]


UPDATE Student SET Age = 20 WHERE Place 3. Which of the following is not a Relational
 = “Bangalore”;
operator? [HY-2019]
The above command will change the age to 20
for those students whose place is “Bangalore”. (a) = (b) = = (c) > = (d) < =
The table will be as updated as below:  [Ans. (b) = = ]

172
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2 MARKS additional questions and Answers

Structured Query Language


1. Define Primary Key Constraint. [QY-2019]
Ans. This constraint declares a field as a Primary key
Choose the Correct Answer 1 MARK
which helps to uniquely identify a record. The 1. Which of the following is a standard
primary key does not allow NULL values and programming language to access and

m
therefore a field declared as primary key must manipulate databases?
have the NOT NULL constraint. (a) MySQL (b) SQL
(c) PHP (d) Python
5 MARKS

co
 [Ans. (b) SQL]
1. Consider the following student table. Write 2. Which of the following language was designed
SQL command for the questions (i) to (v). for managing and accessing data in RDBMS?
 [HY-2019] (a) DBMS (b) DDL
(c) DML (d) SQL

s.
Roll No. Name Group
 [Ans. (d) SQL]
1001 Ganesh A1
3. SQL stands for

ok
1002 Kumar A2 (a) Standard Query Language
1003 Mani B1 (b) Secondary Query Language
(c) Structural Query Language
1004 Raju A1 (d) Standard Question Language
1005 Thulasi A2  [Ans. (c) Structural Query Language]
o
1006 Geetha B1 4. SQL originally called as
(a) DBMS (b) RDBMS
ab

1007 Latha A1 (c) SQL (d) SQLITE


1008 Banu A2  [Ans. (c) SQL]
1009 Kavya B1 5. Find out the odd man out :
(a) MS SQL servers
ur

i) To display the details of all students in (b) Microsoft Access


ascending order of name. (c) IBM DB2
ii) To display all students in A2 group. (d) Dbase [Ans. (d) Dbase]
.s

iii) To display the details group wise. 6. Which of the following is not a RDBMS
package?
iv) To add new row.
(a) Oracle (b) Foxpro
v) To remove students who are in B1 group. (c) DBbase (d) MySQL
w

Ans. i) SELECT*FROM student ORDER BY (e) b and c [Ans. (e) b and c]


name  Asc; 7. The data in RDBMS, is stored in database
objects called
w

ii) SELECT*FROM student GROUP By A2;


(a) Queries (b) Languages
iii) SELECT*FROM Student GROUP By (c) Relations (d) Tables
Group;  [Ans. (d) Tables]
w

iv) INSERT INTO Student (Roll no, Name, 8. Which of the following is a collection of data
 Group) VALUES (10,10, 'Ashish', 'A2'); entries?
v) DELETE FROM Student WHERE Group = (a) Database (b) Table
B1; (c) Dbase (d) SQL
 [Ans. (b) Table]

173
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


9. The specific related information about every 17. Into how many categories the SQL commands
record in the table is maintained by are divided?
Unit IV - Chapter 12

(a) language (b) relation (a) 4 (b) 5 (c) 3 (d) 7


(c) tuple (d) field  [Ans. (b) 5]
 [Ans. (d) field]
18. Which of the following is not a category of

m
10. DDL expansion is SQL command?
(a) Data Defined Language (a) DDL (b) DDL
(b) Data Definition Language (c) DML (d) TCL
(c) Definition Data Language

co
 [Ans. (a) DDL]
(d) Dictionary Data Language
 [Ans. (b) Data Definition Language] 19. DCL stands for
11. DML stand for (a) Dynamic Control Language
(a) Data Manipulation language (b) Data Communication Language

s.
(b) Data Meaningful Language (c) Data Control Language
(c) Directional Manipulate Language (d) Dynamic Data Control Language
(d) Data Management Language  [Ans. (c) Data Control Language]

ok
 [Ans. (a) Data Manipulation language]
20. TCL stands for
12. Which of the following processing skills of (a) Transmission Control Language
SQL provides commands for defining relation (b) Transfer Communication Language
schemes?
(c) Transaction Communication Language
(a) MySQL (b) DDL
o
(d) Transaction control Language
(c) DML (d) DCL
[Ans. (b) Transfer Communication Language]
 [Ans. (b) DDL]
ab

13. Which component of SQL includes commands 21. DQL Stands for
to insert, delete and modify tables in database? (a) Database Query Language
(a) DCL (b) TCL (b) Data Query Language
(c) DDL (d) DML (c) Defined Query Language
ur

 [Ans. (d) DML] (d) Dynamic Query Language


14. Which processing skills of SQL includes  [Ans. (b) Data Query Language]
commands of access rights to creations and 22. Which of the following component simply
views of tables?
.s

deals with description of the database schema?


(a) View definition (b) Integrity (a) DML (b) DDL
(c) Authorization
(c) DCL (d) DQL
(d) Transaction control
w

 [Ans. (b) DDL]


 [Ans. (c) Authorization]
23. Which component provides a self definitions
15. WAMP stands for
to specify storage structure used by the
w

(a) Windows, Android, MySQL, PHP database system?


(b) Windows, Apache, MySQL, Python
(a) DML (b) DQL
(c) Windows, APL, MySQL, PHP
(c) DDL (d) TCL
(d) Windows, Apache, MySQL, PHP
w

 [Ans. (c) DDL]


 [Ans. (d) Windows, Apache, MySQL, PHP]
24. Which of the following is not a SQL DDL
16. Which of the following used to serve live
commands?
websites?
(a) Windows (b) Google (a) Alter (b) Drop
(c) WAMP (d) Google Chrome (c) Grant (d) Truncate
 [Ans. (c) WAMP]  [Ans. (c) Grant]

174
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


25. The SQL DDL command removes all records 33. Revoke command belongs to
from a table and also release the space occupied (a) DML (b) DCL

Structured Query Language


by these records is (c) DQL (d) DDL
(a) Delete (b) Truncate  [Ans. (b) DCL]
(c) Rollback (d) Drop
34. Which of the following commands are used to
 [Ans. (b) Truncate]

m
manage the changes made to the data in table
26. Which of the following SQL DDL command by DML statements?
that delete tables from database? (a) TCL (b) DML
(a) Drop (b) Delete (c) DDL (d) DLL

co
(c) Truncate (d) Rollback  [Ans. (a) TCL]
 [Ans. (a) Drop]
35. Which of the following is not a SQL TCL
27. Which of the following is not a type of DML? command?
(i) Procedural DML (a) Commit

s.
(ii) Non-Procedural DML (b) Roll back
(iii) Programmable DML (c) Revoke
(a) i only (b) ii only (d) Save point [Ans. (c) Revoke]
(c) iii only (d) ii and iii

ok
36. The SQL DQL command used to display all the
 [Ans. (c) iii only]
records from the table is
28. Which DML requires a user to specify what (a) Select (b) display
data is needed without specifying how to get (c) Show (d) Select all
it?  [Ans. (a) Select]
o
(a) Produced DML
(b) Non-Procedural DML 37. Which SQL TCL command save a transaction
(c) Programmable DML temporarily
ab

(d) Procedural DQL (a) Commit (b) Roll back


 [Ans. (b) Non-Procedural DML] (c) Save point (d) None of these
29. The SQL DML command used remove all  [Ans. (c) Save point]
records from a table but not the space occupied 38. Which of the following command used to
ur

by them is retrieve data from a database?


(a) Drop (b) Truncate (a) DDL (b) DQL
(c) Delete (d) Del (c) DML (d) DCL
 [Ans. (c) Delete]  [Ans. (b) DQL]
.s

30. Which of the following used to control the 39. The data in a database is stored based on the
access of data stored in a database? kind of value stored is known as
(a) DCL (b) DML
w

(a) language (b) function


(c) DDL (d) DQL
(c) record (d) datatype
 [Ans. (a) DCL]
 [Ans. (d) datatype]
31. Which of the following SQL DCL command
w

gives permission to one or more users to 40. Which of the following SQL standard
perform specific tasks? recognized only Text and Number data type?
(a) GIVE (b) ORDER (a) ANSI (b) TCL
w

(c) GRANT (d) WHERE (c) DML (d) DCL


 [Ans. (c) GRANT]  [Ans. (a) ANSI]
32. The SQL DCL command withdraws the access 41. Which of the following data type same as real
permission given by the GRANT statement is expect the precision may exceed 64?
(a) WITHDRAWN (b) REMOVE (a) float (b) real
(c) DELETE (d) REVOKE (c) double (d) long real
 [Ans. (d) REVOKE]  [Ans. (c) double]
175
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


42. Double data type precision may exceed 51. Which constraint apply to a group of one or
(a) 64 (b) 74 (c) 54 (d) 14 more columns?
Unit IV - Chapter 12

 [Ans. (a) 64] (a) Column (b) Default


(c) Unique (d) Table
43. Which of the following is not a SQL  [Ans. (d) Table]
predetermined set of commands to work on

m
databases? 52. The constraint enforces a field to always
(a) keywords (b) alters contain a value is
(c) clause (d) commands (a) NULL (b) NOT NULL
 [Ans. (b) alters] (c) YES (d) ALWAYS

co
 [Ans. (b) NOT NULL]
44. Which of the following SQL predetermined
commands are understood as instructions? 53. How many types of database integrity
(a) Arguments (b) Commands constraints are there?
(c) Clause (d) Keywords (a) 4 (b) 5

s.
 [Ans. (d) Keywords] (c) 3 (d) Multiple
 [Ans. (a) 4]
45. Which of the following have a special meaning
in SQL? 54. Which of the following is not a database

ok
(a) Keywords (b) Commands integrity constraint?
(c) Clause (d) Arguments (a) Table (b) Unique
 [Ans. (a) Keywords] (c) Default (d) Check
 [Ans. (a) Table]
46. Which of the following begin with a keyword
o
and consists of keyword and argument? 55. Which of the following constraint ensures
that no two rows have the same value in the
(a) Commands (b) Statement
specified columns?
ab

(c) Clauses (d) Data


(a) Primary key (b) Check
 [Ans. (c) Clauses]
(c) Unique (d) Default
47. Which of the following SQL DDl command  [Ans. (c) Unique]
used to create a table?
56. Which of the following ensures database
ur

(a) CREATE (b) CREATE TABLE integrity constraints?


(c) NEW TABLE (d) DDL TABLE (a) Keywords (b) Keys
 [Ans. (b) CREATE TABLE] (c) Table (d) Constraint
48. Which of the following must be specified when  [Ans. (d) Constraint]
.s

a table is created? 57. Defined multiple constraints are separated by


(a) column name (b) datatype (a) comma (b) space
(c) Size (d) all of these (c) semicolon (d) colon
w

 [Ans. (d) all of these]  [Ans. (b) space]


49. Which of the following are used to limit the 58. Which of the following should be added at the
type of data that can go into a table? end of field definition?
w

(a) Commands (b) Constraint (a) space (b) comma


(c) Keywords (d) Arguments (c) colon (d) semicolon
 [Ans. (b) Constraint]  [Ans. (b) comma]
w

50. Which of the following ensures the accuracy 59. Which of the following constraint helps to
and reliability of the data in the database? uniquely identify a record in the database?
(a) Default (b) Unique
(a) Constraint (b) Table
(c) Primary key (d) Check
(c) Classes (d) Data types  [Ans. (c) Primary key]
 [Ans. (a) Constraint]

176
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


60. Which of the following constraint does not 69. Which of the following command replaces
allow NULL values? some or all data values in a database?

Structured Query Language


(a) Unique (b) Primary key (a) REPLACE (b) UPDATE
(c) Check (d) a and b (c) SET (d) none of these
 [Ans. (b) Primary key]  [Ans. (b) UPDATE]

m
61. Which of the following keyword shows that 70. Which keywords are not used in the command
the field value cannot be empty? used to replace a data value in a database?
(a) NULL (b) NOT NULL (a) UPDATE (b) SET
(c) NO NULL (d) NO VALUE (c) WHERE (d) ADD

co
 [Ans. (b) NOT NULL]  [Ans. (d) ADD]
62. Which constraint helps to set a limit value 71. To update multiple fields with the SET clause
placed for a field? in UPDATE command the field shout be
(a) Default (b) Key separated by
(c) Unique (d) Check

s.
(a) space (b) comma
 [Ans. (d) Check]
(c) colon (d) semi-colon
63. Which of the following constraint use  [Ans. (b) comma]
relational and logical operators for condition?

ok
(a) Primary Key (b) Unique 72. Which of the following keyword not used in
(c) Check (d) Table ALTER command?
 [Ans. (c) Check] (a) ADD (b) MODIFY
64. Which of the following constraint is applied to (c) SET
(d) DROP COLUMN [Ans. (c) SET]
o
a group of field of the table?
(a) Primary Key (b) Table 73. Which of the following command not used to
(c) Properties (d) Unique delete a table?
ab

 [Ans. (b) Table] (a) DELETE (b) TRUNCATE


65. The constraint defined only at the end of table (c) DROP (d) REMOVE
definition is  [Ans. (d) REMOVE]
(a) Table (b) Unique 74. Which command is used to retrieve a subset of
ur

(c) Primary Key (d) Check records from one or more tables?
 [Ans. (a) Table] (a) QUERY (b) SUBSET
(c) SET (d) SELECT
66. Which of the following command helps to add
new records to the table?  [Ans. (d) SELECT]
.s

(a) Insert (b) Add New 75. Which of the following keyword used in
(c) Add row (d) Insert new SELECT command that helps to eliminate
 [Ans. (a) Insert] redundant data?
w

(a) ELIMINATE (b) REDUNDANT


67. In the INSERT command the fields that are (c) DISTINCT (d) DUPLICATE
omitted will have
 [Ans. (c) DISTINCT]
(a) default value (b) Null value
w

76. Which keyword used in SELECT command


(c) No value (d) a or b
that retains duplicate rows?
 [Ans. (b) Null value]
(a) DISTINCT (b) NULL
68. The command to delete all the rows in the
w

(c) RETAIN (d) ALL


table is
 [Ans. (d) ALL]
(a) DELETE ALL FROM tablename
77. The clause in the SELECT command specifies
(b) DELETE tablename
the criteria for getting the desired result is
(c) DELETE * FROM tablename
(a) CHECK (b) DISTINCT
(d) DELETE * FROM tablename ALL
 [Ans. (c) DELETE * FROM tablename] (c) DESIRED (d) WHERE
 [Ans. (d) WHERE]
177
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


78. Which keyword is used to specify the list of Choose and fill in the blanks
values which must be matched with the record 1. _______ allows the user to create, retrieve, alter
Unit IV - Chapter 12

values? and transfer information among databases?


(a) NOT IN (b) BETWEEN (a) SQL (b) DBMS
(c) IN (d) NOT BETWEEN (c) DDL (d) EDBMS

m
 [Ans. (c) IN]  [Ans. (a) SQL]
79. The keyword used to SELECT command 2. A _________ supports the development,
displays only those records that do not match administration and use of database platforms.

co
in the list is (a) SQL (b) DBMS
(a) IN NOT (b) NOT IN (c) MySQL (d) CRUD
(c) NOT BETWEEN (d) NOT WHERE  [Ans. (b) DBMS]
 [Ans. (b) NOT IN] 3. RDBMS is a type of _______ with a row based

s.
table structure that connects related data
80. The keyword used to sort the records in
elements
ascending order is
(a) CRUD (b) SQL
(a) ASCD (b) ASD (c) DBMS (d) Informix

ok
(c) ASCE (d) ASC  [Ans. (c) DBMS]
 [Ans. (d) ASC]
4. A _______ consists of row and columns.
81. The clause used to filter the records in the table is (a) Table (b) Database
(a) ORDER (b) FILTER (c) SQL (d) DBMS
o
(c) WHERE (d) GROUP  [Ans. (a) Table]
 [Ans. (c) WHERE] 5. A_____ is a collection of related fields in a
ab

82. Which clause helps to extract only those table.


records which statify the given condition? (a) Attributes (b) SQL
(a) EXTRACT (b) WHERE (c) Record (d) Relations
 [Ans. (c) Record]
(c) GROUP (d) COMMIT
ur

 [Ans. (b) WHERE] 6. After the database has been created, the data
can be manipulated using ______ procedures.
83. Which keyword is used to divide the table into (a) TCL (b) DCL
groups? (c) DQL (d) DML
.s

(a) DIVIDE BY (b) ORDER BY  [Ans. (d) DML]


(c) GROUP BY (d) HAVING
7. The DML is basically of _______ types
 [Ans. (c) GROUP BY]
w

(a)
3 (b) 2 (c) 4 (d) 5
84. Which clause SELECT command is used to  [Ans. (b) 2]
produce summary report form the database? 8. _______ is used for controlling privileges in
w

(a) GROUP BY (b) REPORT BY the database?


(c) ORDER BY (d) WHERE BY (a) DML (b) DCL
 [Ans. (a) GROUP BY] (c) DDl (d) DQL
 [Ans. (b) DCL]
w

85. Which clause can be used along with GROUP


BY clause and SELECT statement to include 9. All the values in a given field must be of same
aggregate function on them? ________.
(a) WHERE (b) FROM (a) command (b) datatype
(c) record (d) name
(c) HAVING (d) COMMIT
 [Ans. (b) datatype]
 [Ans. (c) HAVING]

178
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. Minimum ________________ colomn is 19. _____ is used with SAVEPOINT command to
required to create a table. jump to a particular savepoint location.

Structured Query Language


(a) One (b) Two (a) COMMINT (b) ROLLBACK TO
(c) Three (d) Four (c) HAVING (d) WHERE
 [Ans. (a) One]  [Ans. (b) ROLL BACK TO]

m
11. _______ is a condition application on a field or Choose the correct pair
set of fields?
(a) Class 1. a) DQL Database Query Language
(b) Control structure b) TCL Transmission Control Language

co
(c) Constraint (d) Arguments c) DCL Data Communication Language
 [Ans. (c) Constraint]
d) DDL Data Definition Language
12. The Primary key constraint is similar to
_______ constraint.  [Ans. (d) DDL – Data Definition Language]

s.
(a) Unique (b) Check 2. a) Update SQL DCL command
(c) Default (d) none of the these
b) Commit SQL TCL command
 [Ans. (a) Unique]
c) Insert SQL DML command

ok
13. The _____ command is used to modify the
table structure (schema) d) Create SQL DDL command
(a) ALTER (b) CHANGE
 [Ans. (c) Insert - SQL DML command]
(c) REPLACE (d) MODIFY
 [Ans. (a) ALTER] Choose the incorrect pair
o
14. A ______ is a command to get a desired result 1. a) Drop SQL DDL command
from the database table.
b) Delete SQL DDL command
ab

(a) TABLE (b) QUERY


(c) FORM (d) REPORT c) Truncate SQL DDL command
 [Ans. (b) QUERY] d) Grant SQL DDL command
15. The _____ keyword is used along with the
[Ans. (b) Delete – SQL DDL command]
SELECT command to eliminate duplicate
ur

rows in the table? 2. a) DCL Data Communication Language


(a) DUPLICATE (b) DISTINCT b) DQL Data Query Language
(c) ELIMINATE (d) a or b c) DCL Data Content Language
.s

 [Ans. (b) DISTINCT]


d) DML Data Manipulation Language
16. The ______ keyword defines a range of values
the record must fall into make the condition [Ans. (a) DCL – Data Communication
true.  Language]
w

(a) BETWEEN (b) RANGE Choose the correct statement


(c) IN (d) WHERE
1. (1) INSERT To student VALUES (104,‘chennai’);
 [Ans. (a) BETWEEN]
w

17. The NULL value in the field can be searched in (2) DELETE ROW FROM student WHERE
a table using the _____ in the WHERE clause.  Admno = 1002;
(a) ==NULL (b) NULL
w

(3) UPDATE student SET Age =18 WHERE city


(c) ISNULL (d) NOT NULL
 = ‘ chennai’;
 [Ans. (c) ISNULL]
18. The _______ symbol is used with the COUNT (4) ALTER TABLE student MODIFY Address
to induce the NULL values.  char (25);
(a) + (b) * (c) >= (d) = (a) 1 (b) 2 (c) 3 (d) 3, 4
 [Ans. (b) *]  [Ans. (d) 3, 4]

179
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose the incorrect statement 2. What is SQL?
Ans. (i) The Structured Query Language (SQL) is a
Unit IV - Chapter 12

1. (1) U nique constraint ensures that no two rows


standard programming language to access
have same value in the specified columns.
and manipulate databases.
(2) Primary Key constraint does not help to
identify a record in the table. (ii) SQL allows the user to create, retrieve, alter,

m
and transfer information among databases.
(3) While creating table, no default value for the
field is assigne(d) (iii) It is a language designed for managing and
(4) Check constraint use only Assignment accessing data in a Relational Data Base
Management System (RDBMS).

co
operator for condition.
(5) Constraints does not ensure database 3. List few RDBMS packages.
integrity.
Ans. Oracle, MySQL, MS SQL Server, IBM DB2 and
(a) 1, 4 (b) 2, 4, 5
Microsoft Access are RDBMS packages.
(c) 4, 5 (d) 3, 4, 5

s.
 [Ans. (c) 4, 5] 4. What is RDBMS ?
Ans. RDBMS is a type of DBMS with a row-based table
2. 1. A LTER command is used to add a new
structure that connects related data elements

ok
column to the table
and includes functions related to Create, Read,
2. ALTER command is used to rename the Update and Delete operations, collectively
existing column name known as CRUD.
3. ALTER command does not change the data
5. Expand
o
type of any column.
(i) DDL
4. ALTER command not used to delete the (ii) DML
ab

column from the table


(iii) WAMP
(a) 3, 4 (b) 1, 2
Ans. (i) DDL - Data Definition Language
(c) 2, 3 (d) only 3 (ii) DML - Data Manipulation
 [Ans. (a) 3, 4] Language
ur

3. (a) T RUNCATE command is used to delete all (iii) WAMP - Windows, Apache,
the rows from the table. MySQL, PHP
(b) DROP TABLE is used to remove a table 6. What is the use of WAMP?
from the database.
.s

Ans. WAMP stands for "Windows, Apache, MySQL


(c) SELECT command is used to retrieve a and PHP" It is often used for web development
subset of records from tables. and internal testing, but may also be used to
(d) While using DROP TABLE command the
w

serve live websites.


table must be empty.
7. Define Data Definition Language.
(e) none of the above
Ans. Functions performed by DDL :
 [Ans. (e) none of the above]
w

(i) The Data Definition Language (DDL)


Very Short Answers 2 MARKS consist of SQL statements used to define
the database structure or schema. It simply
1. Expand
w

deals with descriptions of the database


(i) SQL (ii) DBMS (iii) RDBMS schema and is used to create and modify the
Ans. (i) SQL –Structured Query Language structure of database objects in databases.
(ii) DBMS-Database Management System (ii) 
The DDL provides a set of definitions to
(iii) RDBMS- Relational Database Management specify the storage structure and access
System. methods used by the database system.

180
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


8. List the SQL DDL commands .Explain each. 13. Explain the following SQL TCL commands.
(i) Commit

Structured Query Language


Ans. (i) Create : To create tables in the
database. (ii) Roll back
(ii) Alter :A  lters the structure of the (iii) Save point
database. Ans. (i) Commit : Saves any transaction into the

m
(iii) Drop : Delete tables from database. database permanently.
(iv) Truncate : Remove all records from a (ii) Roll back :Restores the database to last
table, also release the space commit state.

co
occupied by those records. (iii) Save point : Temporarily save a transaction
so that you can rollback.
9. Define Data Manipulation Language.
14. Write the working of the following commands
Ans. (i) A Data Manipulation Language (DML) is
(i) Truncate (ii) Delete
a computer programming language used
(iii) Revoke

s.
for adding (inserting), removing (deleting),
and modifying (updating) data in a Ans. (i) Truncate : Remove all records from a table,
also release the space occupied by those
database.In SQL, the data manipulation
records.

ok
language comprises the SQL-data change
(ii) Delete : Deletes all records from a table, but
statements, which modify stored data but
not the space occupied by them.
not the schema of the database table.
(iii) Revoke : Withdraws the access permission
(ii) 
After the database schema has been
given by the GRANT statement.
o
specified and the database has been created,
the data can be manipulated using a set of 15. Write a note on data query language.
procedures which are expressed by DML. Ans. Data query language : The Data Query
ab

Language consist of commands used to query


10. What are two basic types of DML. or retrieve data from a database. One such SQL
Ans. The DML is basically of two types : command in Data Query Language is
(i) Procedural DML – Requires a user to Select It displays the records from the table.
ur

specify what data is needed and how to get


it. 16. Write the syntax of creating table in database.
(ii) Non-Procedural DML - Requires a user Ans. The syntax of CREATE TABLE command is :
to specify what data is needed without CREATE TABLE <table-name>
.s

specifying how to get it. (<column name><data type>[<size>]


(<column name><data type>[<size>]……
11. List the SQL DML commands. );
w

Ans. (i)  Insert : Inserts data into a table


17. Write the syntax of creating table with
(ii) Update : Updates the existing data
constraint.
within a table.
Ans. The syntax for a table created with constraint is
w

(iii) 
Delete : Deletes all records from given as below:
a table, but not the space CREATE TABLE <table-name>
occupied by them. (<column name><data type>[<size>]
w

12. Define TCL.  <column constraint>,


Ans. Transactional Control Language (TCL) (<column name><data type>[<size>]
commands are used to manage transactions  <column constraint>……
in the database. These are used to manage the <table constraint>(<column name>,
changes made to the data in a table by DML  [<column name>….])…..
statements. );

181
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


18. How will assign a default value for the table 22. Differentiate IN and NOT IN keywords.
field in a data base? Ans.
Unit IV - Chapter 12

Ans. The DEFAULT constraint is used to assign


IN Keyword NOT IN key-
a default value for the field. When no value is
given for the specified field having DEFAULT word
constraint, automatically the default value will The IN keyword is used to The NOT IN

m
be assigned to the field. specify a list of values which keyword displays
Example showing DEFAULT Constraint in the must be matched with the only those records
student table: record values. In other words that do not match

co
CREATE TABLE Student it is used to compare a column in the list.
( with more than one value. It is
Admno integer NOT NULL PRIMARY KEY,
similar to an OR condition.
Name char(20)NOT NULL,

s.
Gender char(1), 23. How will search NULL values in a field? Give
Age integer DEFAULT = “17”, → Default example.
Constraint Ans. The NULL value in a field can be searched in a

ok
Place char(10), table using the ISNULL in the WHERE clause.
); For example to list all the students whose Age
19. Write the syntax of SELECT command for contains no value, the command is used as:
getting the desired result from the table. SELECT * FROM Student WHERE Age IS
o
Ans. The WHERE clause in the SELECT command NULL;
specifies the criteria for getting the desired 24. Write the syntax of ORDER by clause used in
ab

result. The general form of SELECT command SELECT command.


with WHERE Clause is:
Ans. The ORDER BY clause is used as :
Syntax :
SELECT <column-name>[,<co umn-name> SELECT <column-name>[,<columnname>,….]
ur

,….] FROM <table-name>WHERE condition>; FROM <table-name>ORDER BY <column1>,<


 column2>,…ASC| DESC ;
20. How will you retain duplicate rows while
displaying the table? 25. What is the rule to apply DROP TABLE
.s

command?
Ans. The ALL keyword retains duplicate rows. It
will display every row of the table without Ans. The is a condition for dropping a table; is it must
considering duplicate entries. be an empty table.
w

SELECT ALL Place FROM Student; 26. How will you filter the records in a table? Give
21. Differentiate BETWEEN AND NOT an example.
w

BETWEEN keywords. Ans. The WHERE clause is used to filter the records. It
Ans.
helps to extract only those records which satisfy
a given condition. For example in the student
BETWEEN NOT BETWEEN
w

table, to display the list of students of age18 and


The BETWEEN keyword The NOT BETWEEN above in alphabetical order of their names, the
defines a range of values is reverse of the
command is given as below:
the record must fall into BETWEEN operator
where the records not SELECT * FROM Student WHERE Age>=18
to make the condition
satisfying the condition  ORDER BY Name;
true.
are displayed.

182
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


27. Write the syntax of GROUP BY and HAVING SQL commands which come under Data
clause. Control Language are :

Structured Query Language


Ans. SELECT <column-names> FROM <table- Grant Grants permission to one or more
name> GROUP BY <column-name>HAVING users to perform specific tasks.
condition]; Revoke Withdraws the access permission

m
given by the GRANT statement.
28. How will you include aggregate function on
the group created in a table using GROUP BY 3. Write the syntax for the following commands.
clause? (i) INSERT (ii) DELETE

co
Ans. The HAVING clause can be used along with (iii) UPDATE
GROUP BY clause in the SELECT statement
Ans. (i) INSERT :
to place condition on groups and can include
INSERT INTO <table-name>
aggregate functions on them. For example to
 [column-list] VALUES (values);
count the number of Male and Female students

s.
belonging to Chennai . (ii) DELETE :
 SELECT Gender , count(*) FROM Student DELETE FROM table-name WHERE
GROUP BY Gender HAVING Place = ‘Chennai’; condition;

ok
Short Answers 3 MARKS (iii) UPDATE :
UPDATE <table-name> SET column-name
1. How the data in RDBMs is stored ? Explain. = value, column-name = value,… WHERE
Ans. (i)  The data in RDBMS, is stored in database condition;
o
objects, called Tables. A table is a collection
4. List the data types used in SQL.
of related data entries and it consist of rows
and columns. Ans. (i) char (Character)
ab

(ii) A field is a column in a table that is designed (ii) varchar


to maintain specific related information (iii) dec (Decimal)
about every record in the table. It is a (iv) numeric
vertical entity that contains all information (v) int (Integer)
ur

associated with a specific field in a table. The


(vi) smallint
fields in a student table may be of the type
(vii) float
AdmnNo, StudName, StudAge, StudClass,
Place etc. (viii) real
.s

(iii) 
A Record is a row, which is a collection (ix) double
of related fields or columns that exist in 5. How will you frame the commands to work on
a table. A record is a horizontal entity in database?
w

a table which represents the details of a Ans. The SQL provides a predetermined set of
particular student in a student table. commands to work on databases.
2. Define Data Control Language and also list
w

Keywords They have a special meaning in SQL.


the command under this. They are understood as instructions.
Ans. Data control language : A Data Control Commands They are instructions given by the
Language (DCL) is a programming language user to the database also known as
w

used to control the access of data stored in a statements.


database. It is used for controlling privileges Clauses They begin with a keyword and
in the database (Authorization). The privileges consist of keyword and argument.
are required for performing all the database Arguments They are the values given to make
operations such as creating sequences, views of the clause complete.
tables etc.

183
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


6. How will set a primary key for more than one CREATE TABLE Student
field? Explain with example. (
Unit IV - Chapter 12

Ans. Table Constraint : When the constraint is Admno integer NOT NULL PRIMARY KEY
applied to a group of fields of the table, it is Name char(20)NOT NULL,
known as Table constraint. The table constraint is Gender char(1),
normally given at the end of the table definition.

m
Age integer (CHECK<=19), → Check Constraint
Let us take a new table namely Student1 with the
Place char(10),
following fields Admno, Firstname, Lastname,
Gender, Age, Place: );

co
Create Table Student 1 In the above example the check constraint is set
to Age field where the value of Age must be less
(
than or equal to 19.
Admno integer NOT NULL,
Firstname char(20), 9. Write the different categories of SQL
commands.

s.
Lastname char(20),
Gender char(1), Ans. (i) DDL - Data Definition Language
Age integer, (ii) DML - Data Manipulation
Language

ok
Place char(10),
PRIMARY KEY (Firstname, Lastname) → Table (iii) DCL - Data Control Language
constraint (iv) TCL - Transaction Control
); Language
In the above example, the two fields, Firstname (v) DQL - Data Query Language
o
and Lastname are defined as Primary key which
is a Table constraint. Long Answers 5 MARKS
ab

7. How will you generate queries and retrieve 1. Write the processing skills of SQL.
data from the table? Explain?
Ans. The various processing skills of SQL are :
Ans. One of the most important tasks when working (i) Data Definition Language (DDL) : The
with SQL is to generate Queries and retrieve SQL DDL provides commands for defining
ur

data. A Query is a command given to get a relation schemas (structure), deleting


desired result from the database table. The relations, creating indexes and modifying
SELECT command is used to query or retrieve relation schemas.
data from a table in the database. It is used to
(ii) Data Manipulation Language (DML):
.s

retrieve a subset of records from one or more


The SQL DML includes commands to
tables. The SELECT command can be used in
insert, delete, and modify tuples in the
various forms:
database.
w

Syntax of SELECT command :


(iii) Embedded Data Manipulation Language :
SELECT <column-list>FROM<table-name>; The embedded form of SQL is used in high
(i)  Table-name is the name of the table from level programming languages.
which the information is retrieved.
w

(iv) View Definition : The SQL also includes


(ii) Column-list includes one or more columns commands for defining views of tables.
from which data is retrieved. (v) Authorization : The SQL includes
w

8. Which constraint helps to set a limit value commands for access rights to relations and
placed for a field? views of tables.
Ans. Check Constraint : This constraint helps to set (vi) Integrity : The SQL provides forms for
a limit value placed for a field. When we define integrity checking using condition.
a check constraint on a single column, it allows (vii) Transaction control : The SQL includes
only the restricted values on that field. Example commands for file transactions and control
showing check constraint in the student table: over transaction processing.

184
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Explain ALTER command in detail. (xii) To remove the column City from the
Ans. ALTER Command : Student table, the command is used as :

Structured Query Language


(i) The ALTER command is used to alter ALTER TABLE Student DROP COLUMN
the table structure like adding a column, City;
renaming the existing column, change 3. Write a note on

m
the data type of any column or size of the
column or delete the column from the (i) TRUNCATE command.
table. It is used in the following way : (ii) DROP TABLE command.
(ii) ALTER TABLE <table-name> ADD Ans. (i) TRUNCATE command : The TRUNCATE

co
 <column-name><data type><size>; command is used to delete all the rows
(iii) To add a new column “Address” of type from the table, the structure remains and
‘char’ to the Student table, the command is the space is freed from the table. The syntax
used as for TRUNCATE command is:

s.
(iv) ALTER TABLE Student ADD Address ■ TRUNCATE TABLE table-name;
char; For example to delete all the records of the
To modify existing column of table, the student table and delete the table the SQL

ok
ALTER TABLE command can be used with statement is given as follows:
MODIFY clause like wise: ■ TRUNCATE TABLE Student;
(v) ALTER <table-name> MODIFY<column- The table Student is removed and the space
 name><data type><size>; is freed.
ALTER TABLE Student MODIFY Address
o
(ii) DROP TABLE command : The DROP
 char (25);
TABLE command is used to remove a table
(vi) The above command will modify the
ab

from the database. If you drop a table, all


address column of the Student table to now the rows in the table is deleted and the table
hold 25 characters.
structure is removed from the database.
(vii) The ALTER command can be used to Once a table is dropped we cannot get
rename an existing column in the following it back, so be careful while using DROP
ur

way :
TABLE command. But there is a condition
(viii) ALTER <table-name> RENAME old- for dropping a table; it must be an empty
 column- name TO new-column-name; table.
(ix) For example to rename the column Address
.s

 Remove all the rows of the table using


to City, the command is used as :
DELETE command. The DELETE
(x) ALTER TABLE Student RENAME Address command is already explained.
 TO City;
w

To delete all rows, the command is given as:


(xi) The ALTER command can also be used
■ DELETE * FROM Student;
to remove a column or all columns, for
example to remove a particular column, the Once all the rows are deleted, the table can
w

DROP COLUMN is used with the ALTER be deleted by DROP TABLE command in
TABLE to remove a particular field, the the following way:
command can be used as: ■ DROP TABLE table-name;
w

ALTER <table-name> DROP COLUMN For example to delete the Student table:
<column-name>; DROP TABLE Student;


185
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

 
Chapter
PYTHON AND CSV FILES
13

m

co
CHAPTER SNAPSHOT

s.
13.1 Introduction
13.2 Difference between CSV and XLS file formats
13.3 Purpose of CSV File

ok
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
13.4.3 Creating CSV File That contains Double Quotes With Data
o
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
13.6.3 Read A CSV File And Store It In A List
ur

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
13.7.4 CSV Files With Custom Delimiters
w

13.7.5 CSV File With A Line Terminator


13.7.6 CSV File with quote characters
13.7.7 Writing CSV File Into A Dictionary
w

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

[186]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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

m
1. A CSV file is also known as a …. mumbai
(d) chennai,mylapore
(a) Flat File (b) 3D File
mumbai,andheri
(c) String File (d) Random File
 [Ans. (b) mumbai,andheri]

co
 [Ans. (a) Flat File]
8. Which of the following creates an object which
2. The expansion of CRLF is [Govt. MQP-2019] maps data to a dictionary? [PTA-1]
(a) Control Return and Line Feed (a) listreader() (b) reader()
(b) Carriage Return and Form Feed
(c) tuplereader() (d) DictReader ()

s.
(c) Control Router and Line Feed
(d) Carriage Return and Line Feed  [Ans. (d) DictReader ()]
 [Ans. (d) Carriage Return and Line Feed] 9. Making some changes in the data of the

ok
3. Which of the following module is provided by existing file or adding more data is called
Python to do several operations on the CSV (a) Editing (b) Appending
files? (c) Modification (d) Alteration
(a) py (b) xls (c) csv (d) os  [Ans. (c) Modification ]
 [Ans. (c) csv]
o
10. What will be written inside the file test.csv
4. Which of the following mode is used when
using the following program?
dealing with non-text files like image or exe
ab

files? import csv


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

5. The command used to skip a row in a CSV file


is wr.writerows(D)
(a) next() (b) skip() f.close()
(c) omit() (d) bounce() (a) Exam Quarterly Halfyearly
.s

 [Ans. (a) next()] (b) Exam Quarterly Halfyearly


(c) E (d) Exam,
6. Which of the following is a string used to
terminate lines produced by writer()method Q Quarterly,
w

of csv module? H Halfyearly


[Ans. (d) Exam,
(a) Line Terminator (b) Enter key
Quarterly,
(c) Form feed (d) Data Terminator
Halfyearly]
w

 [Ans. (a) Line Terminator]


7. What is the output of the following program? Part - II
import csv Answer the following questions
w

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

187
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(ii) A CSV file is also known as a Flat File that (ii) In this mode, while reading from the file
Unit IV - Chapter 13

can be imported to and exported from 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

m
Python. [PTA-2] files.
Ans. There are two ways to read a CSV file.
2. Write a Python program to modify an existing
(a) Use the csv module’s reader function
file.

co
(b) Use the DictReader class.
Ans. import csv
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:

s.
(ii) 
In this mode, while reading from the file reader = csv.reader(readFile)
the data would be in the format of strings.
lines = list(reader) # list()- to store each
4. What is use of next() function?  row of data as a list

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

#writerows()method writes multiple rows to a csv


5. How will you sort more than one column from file
a csv file? Give an example statement. writer.writerows(lines)
Ans. To sort by more than one column you can use readFile.close()
ur

itemgetter with multiple indices.


writeFile.close()
operator .itemgetter (1,2).
3. Write a Python program to read a CSV file
Syntax : with default delimiter comma (,).
.s

sortedlist = sorted(data, key=operator.itemget Ans. #import csv


ter(Col_number),reverse=True)
import csv #opening the csv file which is in
Part - III  different location with read mode
w

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


 (3 marks) #other way to open the file is f=('c:\\
1. Write a note on open() function of python.
w

pyprg\\sample1.csv','r')
What is the difference between the two
methods? [PTA-1; HY-2019]
reader = csv.reader(F)

Ans. Python has a built-in function open() to open #printing each line of the Data row
w

a file. This function returns a file object, also  by row


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.

188
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Output : Part - IV
['SNO', 'NAME', 'CITY'] Answer the following questions

Python and Csv Files


['12101', 'RAM', 'CHENNAI']  (5 marks)
['12102', 'LAVANYA', 'TIRUCHY'] 1. Differentiate Excel file and CSV file.  [PTA-2]

m
Ans.
[12103', 'LAKSHMAN', 'MADURAI']
Excel CSV
4. What is the difference between the write mode
Excel is a binary file that CSV format is a plain

co
and append mode. [PTA-2, 5] holds information text format with a
Ans. The ‘w’ write mode creates a new file. If the file about all the worksheets in series of values
a file, including separated by commas.
is already existing ‘w’ mode overwrites it. Where
both content and formatting
as ‘a’ append mode is used to add the data at the

s.
end of the file if the file already exists otherwise XLS files can only be read CSV can be opened
by applications with any text editor
creates a new one.
that have been especially in Windows like
5. What is the difference between reader() and written to read their format, notepad, MS Excel,

ok
DictReader() function? and can only be written in OpenOffice, etc.
the same way.
Ans. Reader():
Excel is a spreadsheet that CSV is a format
(i) The reader function is designed to take saves files into its for saving tabular
o
each line of the file and make a list of all own proprietary format viz. information into a
xls or xlsx delimited text file with
columns.
extension .csv
ab

(ii) Using this method one can read data from


Excel consumes more Importing CSV files
csv files of different formats like quotes (" "), memory while importing can be much faster,
pipe (|) and comma (,). data and it also consumes
less memory
(iii) csv. Reader work with list/tuple.
ur

2. Tabulate the different mode with its meaning.


(iv) Syntax: csv.reader(fileobject,delimiter,
Ans.
fmtparams)
Mode Description
.s

DictReaer() :
'r' Open a file for reading. (default)
(i) DictReader works by reading the first 'w' Open a file for writing. Creates a new file
line of the CSV and using each comma if it does not exist or truncates the file if it
w

separated value in this line as a dictionary exists.


key. 'x' Open a file for exclusive creation. If the file
already exists, the operation fails.
w

(ii) DictReader is a class of csv module is used


to read a CSV file into a dictionary. 'a' Open for appending at the end of the file
without truncating it. Creates a new file if it
(iii) It creates an object which maps data to a does not exist.
w

dictionary. 't' Opren in text mode. (default)


(iv) csv.DictReader work with dictionary. 'b' Open in binary mode.
'+' Open a file for updating (reading and
writing)

189
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Write the different methods to read a File in Program :
Unit IV - Chapter 13

Python. #importing csv


Ans. Read a CSV File Using Python :
import csv
There are two ways to read a CSV file.
(i) Use the csv module’s reader function #opening the csv file which is in different
 location with read mode

m
(ii) Use the DictReader class.
with open('c:\\pyprg\\sample1.csv', 'r') as F:
Two ways of Reading CSV File
#other way to open the file is f= ('c:\\pyprg\\

co
 sample1.csv', 'r')
reader = csv.reader(F)
reader () function Dict Reader class
# printing each line of the Data row by row
CSV Module’s Reader Function : print(row)

s.
(i) You can read the contents of CSV file with
F.close()
the help of csv.reader() method. The reader
function is designed to take each line of the Output :

ok
file and make a list of all columns. ['SNO', 'NAME', 'CITY']
(ii) Then, you just choose the column you want ['12101', 'RAM', 'CHENNAI']
the variable data for. Using this method ['12102', 'LAVANYA', 'TIRUCHY']
one can read data from csv files of different
['12103', 'LAKSHMAN', 'MADURAI']
o
formats like quotes (" "), pipe (|) and comma
(,). CSV files - data with Spaces at the beginning
ab

The syntax for csv.reader() is onsider the following file "sample2.csv"


C
csv.reader(fileobject,delimiter,fmtparams) containing the following data when opened
through notepad
where
(iii) file object : passes the path and the mode Topic1, Topic2, Topic3,
ur

of the file one, two, three


(iv) delimiter: an optional parameter Example1, Example2, Example3
containing the standard dilects like , | etc
The following program read the file through
can be omitted.
.s

Python using "csv,reader()".


(v) fmtparams : optional parameter which
import csv
help to override the default values of the
csv.register_dialect('myDialect',delimiter = ',',
w

dialects like skipinitialspace,quoting etc.


can be omitted. skipinitialspace=True)
■ CSV file - data with default delimiter F=open('c:\\pyprg\\sample2.csv','r')
w

comma (,) reader = csv.reader(F, dialect='myDialect')


■ CSV file - data with Space at the for row in reader:
beginning print(row)
w

■ CSV file - data with quotes F.close()


■ CSV file - data with custom Delimiters OUTPUT :
CSV file with default delimiter comma (,): The ['Topic1', 'Topic2', 'Topic3']
following program read a file called “sample1.
csv” with default delimiter comma (,) and print ['one', 'two', 'three']
row by row. ['Example1', 'Example2', 'Example3']
190
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(i) 
These whitespaces in the data can be CSV files with Custom Delimiters :
removed, by registering new dialects using (i) 
You can read CSV file having custom

Python and Csv Files


csv.register_dialect() class of csv module. delimiter by registering a new dialect with
(ii) A dialect describes the format of the csv file the help of csv.register_dialect().
that is to be read.
Roll No Name City

m
(iii) In dialects the parameter "skipinitialspace"
12101 Arun Chennai
is used for removing whitespacesafter the
12102 Meena Kovai
delimiter.

co
CSV File-Data With Quotes : 12103 Ram Nellai

(i) You can read the csv file with quotes, by 103 Ayush M
registering new dialects using csv.register_ 104 Abinandh M
dialect() class of csv module.

s.
(ii) In the following file called "sample4.csv",
(ii) Here, we have quotes.csv file with following each column is separated with | (Pipe
data. symbol)
SNO, Quotes

ok
import csv
1, "The secret to getting ahead is getting
csv.register_dialect('myDialect', delimiter = '|')
started".
with open('c:\\pyprg\\sample4.csv', 'r') as f:
2, "Excellence is a continuous process and not
reader = csv.reader(f, dialect='myDialect')
o
an accident."
The following Program read "quotes.csv" file, for row in reader:
ab

where delimiter is comma (,) bUt the quotes are print(row)


within quotes (" "). f.close()
import csv OUTPUT :
csv.register_dialect('myDialect',delimiter = ',', ['RollNo', 'Name', 'City']
ur

quoting=csv.QUOTE_ALL,
['12101', 'Arun', 'Chennai']
skipinitialspace=True)
['12102', 'Meena', 'Kovai']
f=open('c:\\pyprg\\quotes.csv','r')
.s

['12103', 'Ram', 'Nellai']


reader = csv.reader(f, dialect='myDialect')
4. Write a Python program to write a CSV File
for row in reader: with custom quotes.
w

print(row) Ans. import csv


OUTPUT : info = [[‘SNO’, ‘Person’, ‘DOB’],
['1', 'The secret to getting ahead is getting [‘1’, ‘Madhu’, ‘18/12/2001’],
w

started.']
[‘2’, ‘Sowmya’,’19/2/1998’],
['2', 'Excellence is a continuous process and not
[‘3’, ‘Sangeetha’,’20/3/1999’],
 an accident.']
w

[‘4’, ‘Eshwar’, ‘21/4/2000’],


(i) In the above program, register a dialect
with name myDialect. [‘5’, ‘Anand’, ‘22/5/2001’]]

(ii) 
Then, we used csv. QUOTE_ALL to display csv.register_dialect(‘myDialect’, quoting=csv.
all the characters after double quotes. QUOTE_ALL)

191
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


with open(‘c:\\pyprg\\ch13\\person.csv’, ‘w’) as f: (v) 
Each field may or may not be enclosed in
Unit IV - Chapter 13

writer = csv.writer(f, dialect=’myDialect’) double quotes. If fields are not enclosed


with double quotes, then double quotes
for row in info: may not appear inside the fields.
writer.writerow(row) Example:
f.close() "Red","Blue","Green" #Field data with

m
OUTPUT :  double quotes

"SNO", "Person", "DOB" "1", "Madhu", Black,White,Yellow #Field data without
 double quotes
"18/12/2001" "2", "Sowmya", "19/2/1998"

co
(vi) Fields containing line breaks (CRLF),
"3", "Sangeetha", "20/3/1999" "4", "Eshwar",
double quotes, and commas should be
"21/4/2000" "5", "Anand", "22/5/2001"
enclosed in double-quotes.
5. Write the rules to be followed to format the Example:

s.
data in a CSV file. [PTA-5] Red, “,”, Blue CRLF # comma itself is a field
Ans. Rules to be followed to format data in a CSV value.so it is enclosed with double quotes
file : Red, Blue , Green

ok
(i)  Each record (row of data) is to be located (vii) If double-quotes are used to enclose fields,
on a separate line, delimited by a line break then a double-quote appearing inside a
by pressing enter key. field must be preceded with another double
quote.
Example:
Example:
o
xxx,yyy
 “Red, ” “Blue”, “Green”, # since double
denotes enter Key to be pressed
quotes is a field value it is enclosed with
ab

(ii)  The last record in the file may or may not another double quotes , , White
have an ending line break.
Example: Hands on Experience
ppp, qqq
1. Write a Python program to read the
ur

yyy, xxx
following Namelist.csv file and sort the data
(iii) There may be an optional header line
in alphabetically order of names in a list and
appearing as the first line of the file with the display the output.
same format as normal record lines. The
.s

header will contain names corresponding A B C


to the fields in the file and should contain 1 SNO NAME OCCUPATION
the same number of fields as the records in 2 1 NIVETHITHA ENGINEER
w

the rest of the file.


3 2 ADHITH DOCTOR
Example:
4 3 LAVANYA SINGER
field_name1,field_name2,field_name3
w

5 4 VIDHYA TEACHER
aaa,bbb,ccc
zzz,yyy,xxx CRLF(Carriage Return and 6 5 BINDHU LECTURER
 Line Feed) Ans. import csv.operator
w

data = csv.reader(open('c:\\PYPRG\\NameList.
(iv)  Within the header and each record, there
csv'))
may be one or more fields, separated by next(data)
commas. Spaces are considered part of a sorted list = sorted(data, key = operator.
field and should not be ignored. The last itemgetter(1))
field in the record must not be followed by for row in sorted list:
a comma. For example: Red , Blue print(row)

192
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Output : 3. In csv.register_dialect(), Which of the following
2 Adhith Doctor parameter is used for removing whitespaces?

Python and Csv Files


 [PTA-4]
5 Bindhu Lecturer
(a) removespace (b) skipinitialspace
3 Lavanya Singer
(c) skipspace

m
1 Nivethitha Engineer
(d) removeinitialspace
4 Vidhya Teacher
 [Ans. (b) skipinitialspace]
2. Write a Python program to accept the name

co
4. To read a CSV file into a dictionary can be
and five subjects mark of 5 students .Find the
done by using _____. [PTA-5]
total and store all the details of the students in
a CSV file. (a) Reader (b) DictReader
Ans. import csv (c) CSVReader (d) FileReader

s.
csvData = [['student',   [Ans. (b) DictReader]
'm1','m2','m3','m4','m5','total'],
['Ram', '90','90','90','90','90','450'],
2 MARKS

ok
['Hari', '100','100','100','10','90','490'], 1. What is Excel?  [PTA-6]
['Sai', '90','90','100','100','100','480'], Ans. Excel is a binary file that holds information
['Viji', '100','90','90','90','100','470'] about all the worksheets in a file, including both
['Raja', '80','80','80','100','100','440']] content and formatting.
o
with open('c:\\pyprg\\ch13\\st.csv','w')as CF:
writer = csv.writer(CF) 3 MARKS
ab

writer.writerows(csvData)
1. How csv.write() function is used to create a
CF.close() normal CSV file in Python?  [PTA-4]
Output :
Ans. The csv.writer() method returns a writer object
Student m1 m2 m3 m4 m5 Total
ur

which converts the user’s data into delimited


Ram 90 90 90 90 90 450 strings on the given file-like object. The
Hari 100 100 100 100 90 490 writerow() method writes a row of data into the
specified file.
.s

Sai 90 90 100 100 100 480


Viji 100 90 90 90 100 470 The syntax for csv.writer() is
Raja 80 80 80 100 100 440 csv.writer(fileobject,delimiter,fmtparams)
w

where
PTA Questions and Answers fileobject : passes the path and the mode of the
file
w

1 MARK delimiter : 
an optional parameter containing
1. The file extension of Excel: [PTA-2] the standard dilects like , | etc can be
(a) exl (b) xls (c) cel (d) Ecl omitted
w

 [Ans. (b) xls]


fmtparams : 
optional parameter which
2. The python file mode opens a file for exclusive help to override the default
creation: [PTA-3] values of the dialects like
(a) w (b) x (c) b (d) a skipinitialspace,quoting etc. can
 [Ans. (b) x] be omitted

193
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


 ou can create a normal CSV file using writer()
Y 4. Which of the following can protect if the data
Unit IV - Chapter 13

method of csv module having default delimiter itself contains commas in CSV file?
comma (,) (a) ‘ ‘ (b) , , (c) “ “ (d) :
Here’s an example.  [Ans. (c) “ “]
The following Python program converts a List

m
5. In CSV file, each record is to be located on
of data to a CSV file called “Pupil.csv” that uses, a separate line, delimited by a line break by
(comma) as a value separator. pressing
(a) Enter key (b) ESV key

co
Government Exam Questions and Answers
(c) Tab key (d) Shift key
2 MARKS  [Ans. (a) Enter key]
1. How the CSV file operation takes place in 6. Fields containing line breaks denoted by

s.
python?
(or) (a) CSV (b) XLS
What are the steps involved in file operation of (c) CLRF (d) CRLF
Python?  [Ans. (d) CRLF]

ok
[Govt. MQP-2019]
Ans. Python, a file operation takes place in the 7. In Excel, the default CSV files should open
following order automatically by
Step 1 : Open a file (a) Single click (b) Right click
o
Step 2 : Perform Read or write operation (c) Double click (d) None of these
Step 3 : Close the file  [Ans. (c) Double click]
ab

additional questions and Answers 8. How many ways to read a CSV file?
(a) 2 (b) 3
Choose the Correct Answer 1 MARK
(c) 4 (d) Only one
1. Which of the following gives the python
ur

 [Ans. (a) 2]
programmer the ability to parse CSV files?
(a) CSV data (b) CSV module 9. Which of the following is way to read a CSV
(c) CSV sheet (d) CSV flat file file?
.s

(a) read () (b) reader ()


 [Ans. (b) CSV module]
(c) dictreader () (d) b and c
2. CSV means
 [Ans. (d) b and c]
w

(a) Condition separated values


(b) Colon separated values 10. How many steps are there to do CSV file
(c) C++ solution values operations using python?
w

(d) Comma separated values (a)


2 (b)
3 (c)
4 (d)
5
 [Ans. (d) Comma separated values]  [Ans. (b) 3]
3. Which of the following is a human readable 11. Which of the following built-in function
w

text file where each line has fields?


Python has to open a file?
(a) CSV file
(b) CSV module (a) read () (b) open ()
(c) CSV sheet (c) reader () (d) openfile ()
(d) CSV text [Ans. (a) CSV file]  [Ans. (b) open ()]

194
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


12. Python function open () returns a file object 20. The default file open mode is
called (a) rt (b) x (c) a (d) r

Python and Csv Files


(a) read (b) write  [Ans. (a) rt]
(c) handle (d) process
21. The CSV file contents can be read with the help
 [Ans. (c) handle] of the method

m
13. How many modes can be specified while (a) read ( ) (b) open ( )
opening a CSV file? (c) with open ( ) (d) reader ( )

co
(a) 2 (b) 4  [Ans. (d) reader ( )]
(c) 3 (d) None of these 22. Which of the following function is designed to
 [Ans. (c) 3] take each line of the file and make a list of all
columns?
14. Which of the following is not a mode used

s.
(a) read ( ) (b) reader ( )
while opening a file?
(c) column ( ) (d) list ( )
(a) p (b) w (c) r (d) a
 [Ans. (b) reader ( )]

ok
 [Ans. (a) p]
23. Which of the following format(s) the CSV files
15. CSV file can be opened in
data can be read?
(a) Text mode (b) Binary mode
(a) Quotes (b) Pipe
(c) Application mode (d) a or b
o
(c) Comma (d) all of these
 [Ans. (d) a or b]  [Ans. (d) all of these]
ab

16. Which mode can be used when CSV files 24. How many formats in which CSV file data can
dealing with non-text files? be read?
(a) Read mode (b) Binary mode (a) 3 (b) 2 (c) 4 (d) 5
(c) Process mode (d) Write mode  [Ans. (a) 3]
ur

 [Ans. (b) Binary mode]


25. Which of the following is not a format in which
17. While reading CSV file in text mode, the data CSV file data can be read?
would be in the format (a) Quotes (b) Pipe
.s

(a) numbers (b) characters (c) Semi colon (d) Comma


(c) strings (d) float  [Ans. (c) Semi colon]
w

 [Ans. (c) strings]


26. Which of the following describes the format of
18. Which file mode creates a new file if does not the CSV file that is to be read?
exist? (a) parameter (b) dialect
w

(a) ‘n’ (b) ‘r’ (c) ‘w’ (d) ‘x’ (c) whitespace (d) delimeter
 [Ans. (c) ‘w’]  [Ans. (b) dialect]
w

19. The statement f = open (“sample.txt”) 27. Which of the following allows to create, store
equivalent to the mode and re-use various formatting parameters for
CSV file data?
(a) r (b) x
(a) class (b) dialect
(c) x or a (d) r or r +
(c) object (d) n o n e o f t h e s e
 [Ans. (d) r or r +]
 [Ans. (b) dialect]

195
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


28. The function used to add elements to CSV file 37. Which method returns a writer object which
Unit IV - Chapter 13

is converts the user’s data into delimited strings


(a) add ( ) (b) write ( ) on the given file-like object?
(c) append ( ) (d) addition ( ) (a) csv.write row ( ) (b) csv.write user ( )
 [Ans. (c) append ( )] (c) csv.writer ( ) (d) csv.write ( )

m
29. List literals are enclosed with  [Ans. (c) csv.writer ( )]
(a) { } (b) ( ) (c) < > (d) [ ] 38. Which method writes a row of data into the
specified CSV file?
 [Ans. (d) [ ]]

co
(a) row ( ) (b) writerow ( )
30. In a CSV file, first row should be skipped while
sorting, the function used is (c) rowdata ( ) (d) rowwrite ( )
(a) readonly ( ) (b) readnext ( )  [Ans. (b) writerow ( )]

s.
(c) next ( ) (d) nextrow 39. How many rows at a time the writerrow( )
method writes in a CSV file?
 [Ans. (c) next ( ) ]
(a) 1 (b) 2
31. In CSV file, if more than one column can be

ok
sorted using (c) 3 (d) many
(a) sorter ( ) (b) multisort ( )  [Ans. (a) 1]
(c) itemgetter ( ) (d) morecolumns ( ) 40. Which of the following class of CSV file
 [Ans. (c) itemgetter ( )] module is used to write CSV file with quotes
o
32. CSV. reader ( ) works with the following by registering new dialects?
(a) csv.register ( ) (b) csv.dialect ( )
ab

(a) list tuble (b) set


(c) csv.dialect_register ( )
(c) dictionary (d) b or c
(d) csv.register_dialect ( )
 [Ans. (a) list tube]
 [Ans. (d) csv.register_dialect ( )]
33. CSV dictreader ( ) works with
ur

(a) list (b) tuple 41. Which option allows to write the double quote
or all the values in CSV file?
(c) set (d) dictionary
(a) csv.Quote ( )
 [Ans. (d) dictionary]
.s

(b) csv.ALL_QUOTE()
34. Which of the following works with list /
tupledict? (c) csv.QUOTE_ALL ( )
(d) csv.QUOTEALL ( )
(a) read ( ) (b) dictreader ( )
w

 [Ans. (c) csv.QUOTE_ALL ( )]


(c) reader ( ) (d) dict ( )
 [Ans. (c) reader ( )] 42. The default value of dialect parameter
w

35. Which of the following works with dictionary? skipinitialspace is


(a) True (b) false
(a) reader ( ) (b) dictreader ( )
(c) on (d) off
(c) read ( ) (d) dictionary ( )
w

 [Ans. (b) false]


 [Ans. (b) dictreader ( )]
43. The default line terminator is
36. How many ways are there to write a new or
modify the existing CSV file? (a) \r (b) \n
(a)
8 (b)
6 (c)
4 (d) 2 (c) \b (d) a or b
 [Ans. (d) a or b]
 [Ans. (a) 8]

196
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


44. Which of the following delimiter is considered 2. _______ files are saved with extension.xlsx.
as a column separator? (a) Excel (b) CSV

Python and Csv Files


(a) (b)
, (c)
: (d)
— (c) Wordpad (d) Notepad
 [Ans. (a) ]
 [Ans. (a) Excel]
45. Which method is used to write all the data at

m
3. ______ file cannot store charts or graphs.
once? (a) Excel (b) MsWord
(a) write (b) writer ( )
(c) CSV (d) Openoffice calc
(c) writerow ( ) (d) allrow ( )

co
 [Ans. (c) CSV]
 [Ans. (c) writerow ( )]
4. ______ the extension of CSV file is
46. Which of the following function takes (a) .CV (b) .CSV
additional argument filed names that are used

s.
as dictionary keys fields? (c) .CVS (d) .CS

(i) csv.DictReader ( )  [Ans. (b) .CSV]


(ii) csv.Dicwriter ( ) 5. ____ provides a module named CSV, using this

ok
several operations on the CSV file can be done.
(iii) reader ( ) iv. writer ( )
(a) Ms-Excel (b) Python
(a) i and iii (b) i and ii
(c) iii and iv (d) only iii (c) Text editor (d) Openoffice calc
 [Ans. (b) Python]
o
 [Ans. (b) i and ii]
6. ______ files have been used extensively in
47. Which function is used to print the data in e-commerce.
ab

dictionary format without order?


(a) Ms-Excel
(a) dict ( ) (b) dictionary ( )
(b) Open - Open of file calc
(c) readdict ( ) (d) printdict ( )
(c) Python
 [Ans. (a) dict ( )]
ur

(d) CSV files [Ans. (d) CSV files]


48. By default CSV files should open automatically
7. CSV file name _______ can be represented in
in
the open command using
(a) OpenOffice (b) Python
.s

(a) “ “ (b) ‘ ‘
(c) Excel (d) Text Editor
(c) “”” “”” (d) a or b
 [Ans. (c) Excel]
 [Ans. (d) a or b]
w

49. Which method will free up the resources that 8. CSV files opened in binary mode returns
were tied with the file? ______
(a) free ( ) (b) open ( )
w

(a) bits (b) Mbs


(c) resources ( ) (d) close ( )
(c) bytes (d) GBs
 [Ans. (d) close ( )]
 [Ans. (c) bytes]
w

Choose and fill in the blanks


9. The default mode in which CSV file are opened
1. Files saved in _____ can be opened or edited is________
by text editors.
(a) Excel (b) Worksheet (a) Binary mode (b) Text mode
(c) CSV (d) Python (c) Process mode (d) Write mode
 [Ans. (c) CSV]  [Ans. (b) Text mode]

197
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. In____________ mode, CSV file data format is 17. To sort by more than one column ________
Unit IV - Chapter 13

strings. with multiple indices is used.


(a) read mode (b) write mode (a) sort (b) itemgetter ( )
(c) process mode (d) text mode (c) sorter ( ) (d) more item ( )
 [Ans. (d) text mode]  [Ans. (b) itemgetter ( )]

m
11. ___________ has a garbage collector to clean Very Short Answers 2 MARKS
up unreferenced objects.

co
(a) CSV (b) Excel 1. Why CSV file is known as flat file?
(c) Python (d) Open office Ans. A CSV is known as flat file because files in the
 [Ans. (c) Python] CSV format can be imported to and exported
from programs that store data in tables, such as
12. ____________ command arranges a CSV file

s.
Microsoft Excel or OpenOfficeCalc
list value in ascending order.
(a) listname.sort ( ) 2. What is the use of CSV file?

ok
(b) listname.ascd ( ) Ans. CSV is a simple file format used to store tabular
(c) listname.asc ( ) data, such as a spreadsheet or database. Since
they're plain text, they're easier to import into
(d) sorting ( ) [Ans. (a) listname.sort ( )]
a spreadsheet or another storage database,
13. _______________ takes 1-dimensional data, regardless of the specific software
o
and 2-dimensional to write in a file
3. How will prefect the CSV File data contains
(a) write (b) writerow ( )
ab

common by itself?
(c) row ( ) (d) wrow ( )
Ans. If the fields of data in your CSV file contain
 [Ans. (b) writerow ( )]
commas, you can protect them by enclosing
14. A ________ is a string used to terminate lines those data fields in double-quotes (“). The
ur

produced by writer ( ) commas that are part of your data will then be
(a) Line kept separate from the commas which delimit
(b) Custom Delimiters the fields themselves.
.s

(c) Line Terminator 4. Expand (i) CSV, (ii) CRLF


(d) Quotes [Ans. (c) Line Terminator]
Ans. (i) Comma separated values
w

15. The _____ method sorts the elements of a given (ii) Carriage Return line feed
item in a specific order as same as sort ( ).
(a) reverse sort ( ) (b) sort reverse ( ) 5. How the CSV filename represented in open
command?
w

(c) sorting ( ) (d) sorter ( )


Ans. File name or the complete path name can be
 [Ans. (d) sorter ( )]
represented either with in “ “ or in ‘ ‘ in the open
w

16. Python’s CSV module only accepts command.


____________ as line terminator.
(a) \r (b) \n 6. What take the three models in which CSV file
can be opened ?
(c) \a (d) \r or \n
Ans. Read 'r', write 'w' or append 'a'.
 [Ans. (d) \r or \n]

198
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


7. Differentiate text mode and binary mode. (ii) A dialect describes the format of the csv file
Ans. that is to be read. In dialects the parameter

Python and Csv Files


“skipinitialspace” is used for removing
Text mode Binary mode whitespaces after the delimiter.
The default is Binary mode returns
13. What is dialect?

m
(i) reading in text bytes.
mode. Ans. A dialect is a class of csv module which helps
In this mode, while This is the mode to to define parameters for reading and writing
reading from the be used when dealing CSV. It allows to create, store, and re-use various

co
(ii) file the data would with non-text files like formatting parameters for data.
be in the format of image or exe files.
14. What is list?
strings.
Ans. A list is a data structure in Python that is a

s.
8. Why python has a garbage collector? mutable, or changeable, ordered sequence of
elements.
Ans. Python has a garbage collector to clean up
unreferenced objects but, the user must not rely 15. What is use of sort() method?

ok
on it to close the file. Ans. sort() command arranges a list value in ascending
9. What is the purpose of using 'with' statement order. list_name.sort(reverse) is used to arrange
along with open()? a list in descending order.
Ans. If an exception occurs when you are performing 16. Differentiate sort() and sorted().
o
some operation with the file, the code exits Ans. (i) The sorted() method sorts the elements of
without closing the file. The best way to do this a given item in a specific order – ascending
ab

is using the “with” statement. This ensures that or descending. sort() method performs the
the file is closed when the block inside with is same way as sorted().
exited.
(ii) Only difference, sort() method doesn’t
10. What is the use of close() method? return any value and changes the original
ur

Ans. Closing a file will free up the resources that list itself.
were tied with the file and is done using Python 17. How will you read CSV file into a dictionary?
close() method.
Ans. (i) To read a CSV file into a dictionary can
.s

11. Write a note an reader(). be done by using DictReader class of csv


Ans. (i) To read the contents of CSV file with the module which works similar to the reader()
class but creates an object which maps data
w

help of csv.reader() method. The reader


function is designed to take each line of the to a dictionary.
file and make a list of all columns. (ii) The keys are given by the fieldnames as
parameter.
w

(ii) Then, you just choose the column you want


the variable data for. Using this method 18. How Dict Reader works or What is the use of
one can read data from csv files of different dictionary key?
w

formats like quotes (" "), pipe (|) and comma


Ans. (i) DictReader works by reading the first line of
(,).
the CSV and using each comma separated
12. Write a note is register dialect() method? value in this line as a dictionary key.
Ans. (i) The whitespaces can be removed, by (ii) The columns in each subsequent row then
registering new dialects using csv.register_ behave like dictionary values and can be
dialect() class of csv module. accessed with the appropriate key.

199
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


19. What is the use of dict()? 26. What are the line terminator accepted by
Unit IV - Chapter 13

Ans. The function dict() is used to print the data in python CSV module?
dictionary format without order. Ans. \r and \n are the line terminator accepted by
Python CSV module.
20. What is an Ordered Dict?
27. What are used a dictionary keys?

m
Ans. DictReader() gives OrderedDict by default in its
output. An OrderedDict is a dictionary subclass Ans. csv.DictReader and csv.DictWriter take
which saves the order in which its contents are additional argument fieldnames that are used as
added. To remove the OrderedDict use dict(). dictionary keys.

co
21. Differentiate writer() and writerow()method. Short Answers 3 MARKS
Ans.
1. How will you create CSV normal file?
writer() writerow() Ans. To create a CSV file in Notepad,

s.
The csv.writer() method The writerow() (i) First open a new file using
returns a writer object method writes a row of
which converts the user’s data into the specified File →New or ctrl +N.

ok
data into delimited strings file. (ii) Then enter the data separating each value
on the given file-like object. with a comma and each row with a new
line.
22. What is called modification?
(iii) For example consider the following details
o
Ans. Making some changes in the data of the existing
file or adding more data is called modification. Topic1, Topic2, Topic3
one, two, three
ab

23. Write a program to add new rows in the


existing CSV file? Example1, Example2, Example3
Ans. import csv (iv) Save this content in a file with the extension
row = [‘6’, ‘Sajini ‘, ‘Madurai’] .csv.
ur

with open(‘student.csv’, ‘a’) as CF:


2. How will you save the CSV file in MS-Excel?
# append mode to add data at the end
writer = csv.writer(CF) Ans. To create a CSV file using Microsoft Excel,
launch Excel and then open the file you want to
writer.writerow(row)
.s

save in CSV format. For example, below is the


# writerow() method write a single row of
data contained in our sample Excel worksheet:
 data in file
CF.close()
w

24. Write is purpose of using skipinitialspace


parameter. Item Name Cost - Rs Quantity
w

Ans. The dialect parameter skipinitialspace when it Keyboard 480


5200
12
10
1152
10400
is True, whitespace immediately following the 200 50 2000

delimiter is ignored. The default is False. Total Prof 13552


w

25. Write a note an Line Terminator. Sample Worksheet Data

Ans. A Line Terminator is a string used to terminate


Once the data is entered in the worksheet, select
lines produced by writer. The default value is \r
File → Save As option, and for the “Save as type
or \n. We can write csv file with a line terminator
option”, select CSV (Comma delimited) or type
in Python by registering new dialects using csv.
the file name along with extension .csv.
register_dialect() class of csv module.

200
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Write the syntax of reader(). 7. Write a program to create a new normal CSV
Ans. The syntax for csv.reader() is file to store data.

Python and Csv Files


csv.reader(fileobject,delimiter,fmtparams) Ans. Import csv
where csvData = [[‘Student’, ‘Age’], [‘Dhanush’, ‘17’],
(i) file object : passes the path and the mode  [‘Kalyani’, ‘18’], [‘Ram’, ‘15’]]

m
of the file. with open(‘c:\\pyprg\\ch13\\Pupil.csv’, ‘w’) as
(ii) delimiter : an optional parameter CF:
containing the standard dilects like , | etc writer = csv.writer(CF) # CF is the file object

co
can be omitted writer.writerows(csvData) # csvData is the List
(iii) fmtparams : optional parameter which name
help to override the default values of the CF.close()
dialects like skipinitialspace,quoting etc.
Can be omitted. Long Answers 5 MARKS

s.
4. Write a program to read a file with default 1. Write a program to read the CSV file through
delimiter comma. python using reader () method.
Ans. #importing csv

ok
Ans. import csv
import csv csv.register_dialect('myDialect',delimiter =
#opening the csv file which is in different ',',skipinitialspace=True)
 location with read mode
F=open('c:\\pyprg\\sample2.csv','r')
with open('c:\\pyprg\\sample1.csv', 'r') as F:
o
reader = csv.reader(F, dialect='myDialect')
#other way to open the file is f= ('c:\\pyprg\\
 sample1.csv', 'r') for row in reader:
ab

reader = csv.reader(F) print(row)


# printing each line of the Data row by row F.close()
print(row) 2. Write a program to read the CSV file which
F.close() contains spaces after the delimiter.
ur

Ans. import csv


5. What are the different ways of reading a CSV file
using reader() method? csv.register_dialect('myDialect',delimiter =
Ans. (i)  CSV file - data with default delimiter ',',skipinitialspace=True)
.s

comma (,) F=open('c:\\pyprg\\sample2.csv','r')


(ii) CSV file - data with Space at the beginning reader = csv.reader(F, dialect='myDialect')
(iii) CSV file - data with quotes for row in reader:
w

(iv) CSV file - data with quotes print(row)


6. What are the ways to write a new or edit are F.close()
existing CSV file in python? 3. Write a program to read the CSV file with user
w

Ans. (i) Creating A New Normal CSV File defined delimiter.


(ii) Modifying An Existing File Ans. Import csv
(iii) Writing on a CSV File with Quotes csv.register_dialect('myDialect', delimiter = '|')
w

(iv)  Writing on a CSV File with Custom Delimiters with open('c:\\pyprg\\sample4.csv', 'r') as f:
(v) Writing on a CSV File with Lineterminator reader = csv,reader(f, dialect='myDialect')
(vi) Writing on a CSV File with Quotechars
for row in reader:
(vii) Writing CSV File Into A Dictionary
print(row)
(viii) Getting Data At Runtime And Writing In a
File f.close()

201
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. Write a program to read a specific column in F=open(inFile,’r’)
Unit IV - Chapter 13

a CSV file. # reading the File with the help of csv.reader()


Ans. Import csv reader = csv.reader(F)
# skipping the first row(heading)
#opening the csv file which is in different
next(reader)
 location with read mode

m
# declaring a list
f=open("c:\\pyprg\\ch 13sample5.csv",'r') arrayValue = []
#reading the File with the help of csv.reader() a = int(input (“Enter the column number 1 to
3:-“))

co
readFile=csv.reader(f)
# sorting a particular column-cost
#printing the selected column for row in reader:
for col in readFile : arrayValue.append(row[a])
print col[0],col[3] arrayValue.sort()

s.
for row in arrayValue:
f.close()
print (row)
Sample5.csv File in Excel F.close()

ok
5. Write a program to read the CSV file and store 7. How will you sort more than one column in a
it in a list. CSV file? Explain with an example.
Ans. import csv Ans. To sort by more than one column you can use
itemgetter with multiple indices: operator.
o
# other way of declaring the filename
itemgetter (1,2).
inFile= 'c:\\pyprg\\sample.csv' sample8.csv in Excel screen
ab

F=open(inFile,'r')
reader = csv.reader(F)
# declaring array Item Name Quantity
Keyboard 48
ur

arrayValue = [] Monitor
Mouse
52
20

# displaying the content of the list


for row in reader:
.s

arrayValue.append(row)
print(row) ItemName ,Quantity
sample8.csv in Notepad

Keyboard, 48
w

F.close() Monitor,52
Mouse ,20
6. Write a program to read the CSV file and store CSV file Data into a list for sorting

A column value in A list for sorting.


 e following program do the task mentioned
Th
w

Ans. # sort a selected column given by user leaving above using operator.itemgetter(col_no)
 the header column Example :
import csv # Program to sort the entire row by using a
w

# other way of declaring the filename  specified column.


inFile= ‘c:\\pyprg\\sample6.csv’ # declaring multiple header files
import csv ,operator
# opening the csv file which is in the same
 location of this #One more way to read the file
data = csv.reader(open(‘c:\\PYPRG\\sample8.csv’))
python file
next(data) #(to omit the header)

202
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


#using operator module for sorting multiple csv.register_dialect(‘myDialect’,delimiter = ‘|’,
columns  quotechar = ‘”’, quoting=csv.QUOTE_ALL)

Python and Csv Files


sortedlist = sorted (data, key=operator. with open(‘c:\\pyprg\\ch13\\quote.csv’, ‘w’) as 
itemgetter(1)) # 1 specifies we want to sort csvFile:
# according to second column writer = csv.writer(csvFile,

m
for row in sortedlist:
dialect=’myDialect’)
print(row)
writer.writerows(csvData)
Output :
print(“writing completed”)
[‘Mouse ‘, ‘20’]

co
csvFile.close()
[‘Keyboard ‘, ‘48’]
11. How will you write Dictionary into CSV file
[‘Monitor’, ‘52’] with custom dialects?
8. Write a program to read CSV file with user Ans. import csv
Defined Delimiter into a Dictionary. csv.register_dialect(‘myDialect’, delimiter = ‘|’,

s.
Ans. import csv quoting=csv.QUOTE_ALL)
csv.register_dialect(‘myDialect’,delimiter = with open(‘c:\\pyprg\\ch13\\grade.csv’, ‘w’) as
csvfile:

ok
‘|’,skipinitialspace=True)
filename = ‘c:\\pyprg\\ch13\\sample8.csv’ fieldnames = [‘Name’, ‘Grade’]
with open(filename, ‘r’) as csvfile: writer = csv.DictWriter(csvfile,
reader = csv.DictReader(csvfile, fieldnames=fieldnames, dialect
dialect=’myDialect’) =”myDialect”)
o
writer.writeheader()
for row in reader:
writer.writerows([{‘Grade’: ‘B’, ‘Name’:
print(dict(row))
ab

‘Anu’},
csvfile.close()
{‘Grade’: ‘A’, ‘Name’: ‘Beena’},
9. Write a program to read CSV file with a line {‘Grade’: ‘C’, ‘Name’: ‘Tarun’}])
Terminator.
print(“writing completed”)
Ans. import csv 12. Write a program to set data at runtime and
ur

Data = [[‘Fruit’, ‘Quantity’], [‘Apple’, ‘5’], writing it in a CSV file.


 [‘Banana’, ‘7’], [‘Mango’, ‘8’]] Ans. import csv
csv.register_dialect(‘myDialect’, delimiter with open(‘c:\\pyprg\\ch13\\dynamicfile.csv’,
 = ‘|’, lineterminator = ‘\n’)  ‘w’) as f:
.s

with open(‘c:\\pyprg\\ch13\\line.csv’, ‘w’) as f: w = csv.writer(f)


writer = csv.writer(f, dialect=’myDialect’) ans=’y’
while (ans==’y’):
w

writer.writerows(Data)
name = input(“Name?: “)
f.close()
date = input(“Date of birth: “)
10. How will you write the CSV file with custom place = input(“Place: “)
w

denote characters? Explain with an example. w.writerow([name, date, place])


Ans. To write the CSV file with custom quote ans=input(“Do you want to enter more
characters, by registering new dialects using csv.  y/n?: “)
register_dialect() class of csv module.
w

F=open(‘c:\\pyprg\\ch13\\dynamicfile.csv’,’r’)
Example : reader = csv.reader(F)
import csv for row in reader:
csvData = [[‘SNO’,’Items’], [‘1’,’Pen’], [‘2’,’Book’], print(row)
[‘3’,’Pencil’]] F.close()


203
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science

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

m
Importing C++

co
Chapter
Programs in Python
14

s.
CHAPTER SNAPSHOT
14.1 Introduction
o ok
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++
14.6.1 Module
.s

14.6.2 How to import modules in Python?


14.7 Python program Executing C++ Program using control statement
14.8 How Python is handling the errors in C++
w

14.9 Python program Executing C++ Program Containing Arrays


14.10 Python program Executing C++ Program Containing Functions
14.11 Python program to Illustrate the inheritance of a Class
w
w

[204]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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

m
1. Which of the following is not a scripting  [Ans. (b)__name__]
language? 9. Which of the following can be used for
(a) JavaScript (b) PHP processing text, numbers, images, and

co
(c) Perl (d) HTML scientific data?
 [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]
10. What does __name__ contains ? [PTA-6]

s.
(a) wrapping (b) Downloading
(c) Interconnecting (d) Parsing (a) c++ filename (c) main() name
[Ans. (a) wrapping] (c) python filename (d) os module name
[Ans. (C) python filename]

ok
3. The expansion of API is
(a) Application Programming Interpreter
Part - II
(b) Application Programming Interface Answer the following questions
(c) Application Performing Interface  (2 marks)
(d) Application Programming Interlink
o
1. What is the theoretical difference between
[Ans. (b) Application Programming Scripting language and other programming
Interface] language?
ab

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

needs to be compiled before running


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

(a) Object oriented Programming while a programming language requires a


(b) Modular programming compiler.
(c) Low Level Programming 2. Differentiate compiler and interpreter.
w

(d) Procedure oriented Programming Ans.  [Govt. MQP-2019]


[Ans. (b) Modular programming] S.No Compiler Interpreter
6. The module which allows you to interface with (i) Compiler generates Interpreter
w

the Windows operating system is an Intermediate generates Machine


(a) OS module (b) sys module Code. Code.
(c) csv module (d) getopt module (ii) Compiler reads Interpreter reads
entire program for single statement
w

[Ans. (a) OS module]


compilation. at a time for
7. getopt() will return an empty array if there is interpretation.
no error in splitting strings to (iii) Error deduction is Error deduction is
(a) argv variable (b) opt variable difficult. easy.
(c) args variable (d) ifile variable (iv) Comparatively faster. Slower.
[Ans. (c) args variable] (v) Example : C++ Example : Python

205
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Write the expansion of (i) SWIG (ii) MinGW (iii) Less code intensive as compared to
Unit V - Chapter 14

 [PTA-1, 5] 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?

m
Ans. (i) MinGW refers to a set of runtime header
4. What is the use of modules?
files, used in compiling and linking the
Ans. (i) The use of modules to break down large code of C, C++ and FORTRAN to be run

co
programs into small manageable and on Windows Operating System.
organized files. (ii) MinGw-W64 (version of MinGW) is the
(ii) Modules provide reusability of code. Define best compiler for C++ on Windows. To
our most used functions in a module compile and execute the C++ program, you
and import it, instead of copying their

s.
need ‘g++’ for Windows. MinGW allows
definitions into different programs. to compile and execute C++ program
5. What is the use of cd command. Give an dynamically through Python program
using g++.

ok
example.
Ans. ‘cd’ command refers to change directory and (iii) Python program that contains the C++
absolute path refers to the couple path. coding can be executed only through
(Eg) “cd c:\program files\open office 4\program” minGW-w64 project’ run terminal. The run
terminal open the command-line window
o
Part - III through which Python program should be
Answer the following questions executed.
ab

 (3 marks) 4. Identify the module, operator, definition name


for the following.
1. Differentiate PYTHON and C++. [HY-2019]
Ans. welcome.display() [PTA-6]
Ans. Welcome → Module name
S.
ur

PYTHON C++ · → Dot operator


No
display() → Function call
Python is typically C++ is typically a
(i) an "interpreted" "compiled" language 5. What is sys.argv? What does it contain?
.s

language Ans. sys.argv is the list of command-line arguments


Python is a C++ is compiled passed to the Python program. argv contains
(ii) dynamic-typed statically typed all the items that come along via the command-
w

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.
(iii) required while while declaring main(sys.argv[1]) :
w

declaring variable variable (i)  Accepts the program file (Python


It can act both It is a general program) and the input file (C++ file) as a
as scripting and purpose language list(array).
(iv)
w

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] 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.

206
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Part - IV (ii) To use sys.argv, you will first have to
import sys. The first argument, sys.argv[0],

Importing C++ Programs in Python


Answer the following questions is always the name of the program as it
 (5 marks) was invoked, and sys.argv[1] is the first
argument you pass to the program (here it
1. Write any 5 features of Python. [PTA-3] is the C++ file).

m
Ans. (i) Python uses Automatic Garbage Collection. (ii) Python's OS Module :
(ii) Python is a dynamically typed language. (i) The OS module in Python provides a
(iii) Python runs through an interpreter. way of using operating system dependent
functionality.

co
(iv) Python code tends to be 5 to 10 times
shorter than that written in C++. (ii) The functions that the OS module allows
you to interface with the Windows
(v) In Python, there is no need to declare types
operating system where Python is running
explicitly.
on.
(vi) In Python, a function may accept an

s.
os.system():
argument of any type, and return multiple (i) Execute the C++ compiling command (a
values without any kind of declaration string contains Unix, C command which
beforehand. also supports C++ command) in the shell

ok
2. Explain each word of the following command. (Here it is Command Window).
(ii) For Example to compile C++ program g++
Python <filename.py> -<i> <C++ filename compiler should be invoked.
 without cpp extension> (iv) Command : os.system (‘g++’ + <varaiable_
name1> ‘-<mode>’ + <variable_name2>
o
Ans. Python <filename.py> -i <C++ filename without
cpp extension> (i) os.system function system() defined
where, in os module
ab

Python Keyword to execute the (ii) g++ General compiler to


Python program from compile C++ program
command-line under Windows Operating
system.
filename.py Name of the Python
ur

(iii) variable_name1 Name of the C++ file


program to executed
without extension.cpp in
-i input mode string format
C++ filename Name of C++ file to be (iv) mode To specify input or output
.s

without cpp compiled and executed mode. Here it is o prefixed


extension with hyphen.
Python getopt module :
3. What is the purpose of sys, os, getopt module
w

in Python? Explain. (i) The getopt module of Python helps you to


Ans. (i) Python's sys module : This module parse (split) command-line options and
provides access to some variables used arguments.
w

by the interpreter and to functions that (ii) This module provides two functions to
interact strongly with the interpreter. enable command-line argument parsing.
sys.argv : (iii) Python getopt.getopt method :
w

(i) sys.argv is the list of command-line (i) This method parses command-line options
arguments passed to the Python program.
and parameter list. Following is the syntax
argv contains all the items that come
for this method −
along via the command-line input, it's
basically an array holding the command- (ii) <opts>,<args>=getopt.getopt(argv, options,
line arguments of the program. [long_options])

207
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


■ a rgv - This is the argument list of 4. Write the syntax for getopt() and explain its
values to be parsed (splited). In our arguments and return values.
Unit V - Chapter 14

[PTA-2, 5]
program the complete command will Ans. Python getopt Module :
be passed as a list. (i) The getopt module of Python helps you to
■  options - This is string of option parse (split) command-line options and
letters that the Python program arguments.

m
recognize as, for input or for output, (ii) This module provides two functions to
with options (like 'i' or 'o') that enable command-line argument parsing.
followed by a colon (:).  getopt.getopt method : This method parses

co
command-line options and parameter list.
 Here colon is used to denote the Following is the syntax for this method −
mode. <opts>,<args>=getopt.getopt(argv, options,
■  long_options - This parameter is [long_options])
passed with a list of strings. Argument Here is the detail of the parameters −

s.
of Long options should be followed (i) argv : This is the argument list of values
by an equal sign ('='). to be parsed (splited). In our program the
■ In our program the C++ file name complete command will be passed as a list.
(ii) options : This is string of option letters that

ok
will be passed as string and 'i' also will
be passed along with to indicate it as the Python program recognize as, for input
the input file. or for output, with options (like ‘i’ or ‘o’)
that followed by a colon (:). Here colon is
(iv) getopt() method returns value consisting
used to denote the mode.
of two elements.
o
(iii) long_options : This parameter is passed
(v) Each of these values are stored separately
with a list of strings. Argument of Long
in two different list (arrays) opts and args. options should be followed by an equal sign
ab

(vi) Opts contains list of splitted strings like ('='). In our program the C++ file name
mode, path and args contains any string if will be passed as string and ‘i’ also will be
at all not splitted because of wrong path or passed along with to indicate it as the input
mode. file.
(vi) args will be an empty array if there is no
ur

 getopt() method returns value consisting of


error in splitting strings by getopt(). two elements. Each of these values are stored
(vii) Example : separately in two different list (arrays) opts and
(viii) opts, args = getopt.getopt (argv, args. Opts contains list of splitted strings like
.s

"i:",['ifile=']) mode, path and args contains any string if at


all not splitted because of wrong path or mode.
■ where opts contains - ('i', 'c:\\pyprg\\
args will be an empty array if there is no error in
p4')]
splitting strings by getopt().
w

■ -i: - option nothing but mode should


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

the absolute path of C++ file.


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

argument args will be empty []. -i :- option nothing but


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

208
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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

m
Rno integer
5. Write a Python program to execute the
Public members
following c++ coding
void Readno(int); to accept roll number and
#include <iostream> assign to Rno

co
using namespace std; void Writeno(); To display Rno.
int main() The class Test is derived Publically from the
Student class contains the following details
{ cout<<“WELCOME”;
Protected member
return(0);
Mark1 float

s.
} Mark2 float
The above C++ program is saved in a file Public members
welcome.cpp void Readmark(float, float); To accept mark1

ok
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
# Program that compiles and executes a .cpp file detail
# Python main.py -i welcome Protected members
o
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
for o, a in opts: Private member
ur

if o in ("-i", "--ifile"): Total float


cpp_file = a + '.cpp' Public member
void display() assign the sum of mark1, mark2,
exe_file = a + '.exe' score in total.
.s

run(cpp_file, exe_file) invokeWriteno(), Writemark() and Writescore().


def run(cpp_file, exe_file): Display the total also.
print("Compiling " + cpp_file) Save the C++ program in a file called hybrid.
w

Write a python program to execute the


os.system('g++ ' + cpp_file + ' -o ' + exe_ file) hybrid.cpp
print("Running " + exe_file) Ans. In Notepad, type the C++ program.
w

print("-------------------------") #include<iostream>
print using namespace std;
os.system(exe_file) class student
{
w

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

209
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


void writeno() save this file as hybrid.cpp
{ Now type the python program in New Notepad
Unit V - Chapter 14

cout<<"\n Roll no."<<rno; file.


}}; #python hybrid.py -i hybrid.cpp
class test: public student import sys,os,getopt
{ def main(argv);

m
protected:
cpp_file="
float mark1,mar2;
public: exe_file="
void readmark(float m1, float m2) opts, args = getopt.getopt(argv, "i:",

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

s.
{ run(cpp_file, exe_file)
cout<<"\n mark1"<<mark1; def run(cpp_file, exe_file)
cout<<"\n mark2"<<mark2;
print("Compiling"+cpp_file)
}};

ok
class sports os.system('g++'+ cpp_file + '-o'+ exe_file)
{ print("Running" + exe_file)
protected: print("------------------")
int score; print
public: os.system(exe_file)
o
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
float total;
.s

elements of a matrix and name the file as


public;
Border.cpp. Write a python program to execute
void display()
the Border.cpp
{
Ans. Select File → New in Notepad and type the C++
w

total = mark1 + mark2;


cout<<"TOTAL MARKS: "<<total; program.
}}; #include<iostream>
int main() #include<bits/stdc++.h>
w

{ using namespace std;


result r; const int MAX = 100;
r.readno(5); void printBoundary(int a[][max], int m, int n)
r.readmark(100,100); {
w

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]<<" ";

210
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

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

m
}} which by default stores the name of the file?
 [PTA-1]
int main()
(a) __name__ (b) __init__
{

co
(c) __del__ (d) __def__
int a[4][MAX] = { {1,2,3,4}, {5,6,7,8},
 {1,2,3,4}, {5,6,7,8}};  [Ans. (a) __name__]
print Boundary(a,4,4); 2. _______ is a built-in variable which evaluates
return 0; to the name of the current module. [PTA-4]

s.
} (a) __name__ (b) __main__
save it as Border.cpp (c) __mode__ (d) __init__
open a New notepad file and type the python  [Ans. (a) __name__]

ok
program to execute border.cpp
additional questions and Answers
#python border.py -i border.cpp
import sys,os,getopt Choose the Correct Answer 1 MARK
def main(argv):
1. Which of the following are general purpose
o
cpp_file =" programming language?
exe_file =" (a) Python (b) C++
ab

opts, args= getopt.getopt(argv, "i:", (c) Java (d) All of these


['ifile="])  [Ans. (d) All of these]
for o, a in opts:
2. Which of the following is not general purpose
if o in("-i", "--ifile"):
language?
ur

cpp_file = a+'.cpp'
(a) Python (b) Perl
exe_file = a+'.exe'
(c) Java (d) C++
run(cpp_file, exe_file)  [Ans. (b) Perl]
def run(cpp_file, exe_file):
.s

3. Which of the following is not a compiled


print("Compiling" + cpp_file) statically typed language?
os.system('g++'+ cpp_file + '-o'+ exe_file) (a) C++ (b) Java
print("Running" + exe_file) (c) Python (d) All of these
w

print("---------------") [Ans. (c) Python]


print 4. In which language datatype or not required
w

os.system(exe_file) while declare variable?


print (a) C++ (b) C
if__name__=='__main__': (c) Java (d) Python
w

main(sys.argv[1:])  [Ans. (d) Python]


Output : 5. Which of the following can act both as
1 2 3 4 scripting and general purpose language?
5 8
1 4 (a) Python (b) C
5 6 7 8 (c) C++ (d) Html
 [Ans. (a) Python]

211
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


6. Which programming language is useful 14. Which of the following interface used for
when the logic can be written in C++ and
Unit V - Chapter 14

interfacing with C programs?


manipulated through python program?
(a) MicGW (b) Boost
(a) C++ (b) Python
(c) Ctypes (d) Cython
(c) Perl (d) Html
 [Ans. (c) Ctypes]

m
 [Ans. (b) Python]
7. Which is a programming language designed 15. SWIG expansion is
for integrating and communicating with other (a) Simplified Wrapper Interface Generator

co
programming languages? (b) Software Wrapper Information Generator
(a) Modular language (c) Simplified Wrapper Interface Generator
(b) Procedural language (d) System Wrapper Interface Generator
(c) Scripting language
 [Ans. (a) Simplified Wrapper Interface
(d) Procedural language

s.
Generator]
 [Ans. (a) Modular language]
8. Which of the following is a scripting language? 16. Which of the following python interface used
for both C and C++?

ok
(a) Ruby (b) ASP
(c) TCl (d) All of these (a) MinGW (b) Ctypes
 [Ans. (d) All of these] (c) Cython (d) SWIG
9. Which of the following language used  [Ans. (d) SWIG]
o
automatic garbage collection? 17. MinGW expansion is
(a) C++ (b) Java
(a) Minimalist Graphics for windows
ab

(c) C (d) Python


(b) Minimum GNU for windows
 [Ans. (d) Python]
(c) Minimalist GNU for windows
10. A scripting language requires (d) Motion Graphics for windows
(a) Compiler (b) Interpreter  [Ans. (c) Minimalist GNU for windows]
ur

(c) Python (d) Modules


18. Which of the following is needed to run a C++
 [Ans. (b) Interpreter]
program on windows?
11. A programming language requires (a) m++ (b) g++
.s

(a) Complier (c) ghre++ (d) f++


(b) Interpreter  [Ans. (b) g++]
(c) Modules
19. The command to change to the folder where
w

(d) Scripts
Python is located is
 [Ans. (b) Interpreter]
(a) Change (b) CD
12. C++ code is 5 to 10 times more than (c) Dir (d) CDir
w

(a) Java (b) Python  [Ans. (b) CD]


(c) C (d) Java script
20. The syntax to execute the python program is
 [Ans. (b) Python]
w

(a) Python –i <filename.Py> <C++ filename>


13. How many ways are there to create python (b) Python <filename – py> <C++ filename> -i
interface? (c) Python <C++ filename> -i <filename.py>
(a) 4 (b) 3
(d) Python <filename.py> -i <C++ filename>
(c) 5 (d) Many
 [Ans. (d) Python <filename.py> -i <C++
 [Ans. (d) Many] filename>]

212
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


21. In the command python <filename.py> - i 30. Which of the following definition invoke the
‘g++’ compiler and creates the exe file?

Importing C++ Programs in Python


<C++ filename> where i denotes.
(a) Information (b) Input mode (a) Main (b) Name
(c) ios (d) Interpreter (c) Run (d) System
[Ans. (b) Input mode]  [Ans. (c) Run]

m
Match the following
22. Which of the following is not a python module? 1. 1 PHP Interface with C
(a) OS (b) Sys 2 HTML Interface generator

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

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

ok
(a) Sys (b) OS Choose the odd man out
(c) Getopt (d) g++
1. (a) Java (b) Python
 [Ans. (d) g++]
(c) HTML (d) C++[Ans. (b) Python]
25. Which of the following is a python module?
o
(a) Sys (b) OS
Choose and fill in the blanks
(c) Getopt (d) All of these 1. ______ is typically interpreted language.
ab

 [Ans. (d) All of these] (a) Python (b) Java


(c) C++ (d) None of these
26. Which of the following is an array holding the
command line arguments of the program?  [Ans. (a) Python]
(a) g++ (b) argv
ur

2. ______ is mostly used as a ‘glue’ language.


(c) Opts (d) Getopt
(a) C++ (b) Java
 [Ans. (b) argv]
(c) Python (d) CSV
27. How many options getopt provides to enable
.s

 [Ans. (c) Python]


command line argument parsing?
(a) 3 (b) 7 (c) 2 (d) 4 3. _______ is both a python like language for
 [Ans. (c) 2] writing C extensions.
w

(a) Boost
28. Getopt () method returns values are started in
(b) Cython
(a) Opts (b) Args
(c) SWIG
w

(c) Sys (d) a and b


(d) Ctypes [Ans. (b) Cython]
 [Ans. (d) a and b]
4. _____ refers to a set of runtime header files
29. The mode ‘i’/’o’ parses each values of the
w

used in compiling and linking the C++ code to


command line and pass as argument to the list
called be run or window OS?
(a) Args (b) Opts (a) SWIG (b) MinGW
(c) Sys (d) Argv (c) Cython (d) Boost
 [Ans. (b) Opts]  [Ans. (b) MinGW]

213
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5. ______ version of MinGW is the best compiler 11. _______ is the list of command-line argument
passed to the python program?
Unit V - Chapter 14

for C++ on windows.


(a) W32 (b) W128 (a) OS.system ()
(b) Getopt.getopt ()
(c) W256 (d) W64
(c) Sys.argv

m
 [Ans. (d) W64]
(d) Next () [Ans. (c) Sys.argv]
6. _____ allows to compile and execute C++ 12. To use sys.argv, you have to ______
program dynamically through python

co
(a) Import CSV (b) Import.+ py
program using g++.
(c) Import sys (d) Include sys
(a) MinGW (b) Ctypes
 [Ans. (c) Import sys]
(c) Boost (d) SWIG

s.
 [Ans. (a) MinGW] 13. ___ symbol is os.system () indicates that all
strings are concatenated and send that as a list.
7. ______ is a program that calls GCC for linking (a) + (b) . (c) () (d) _
the C++ library files to the object code.

ok
 [Ans. (a) +]
(a) C++ (b) C
(c) Python (d) g++ 14. _____ module of python helps you to split
 [Ans. (d) g++] command line options and arguments.
(a) OS (b) Getopt
o
8. _______ refers to the complete path where
python is installed. (c) Sys (d) All of these
 [Ans. (b) Getopt]
ab

(a) Relative path


(b) Python path 15. ______ method returns value consisting of
(c) Absolute path two elements.
(d) Directory path [Ans. (c) Absolute path] (a) sys.argv
ur

(b) oS.system ()
9. ______ is a software design technique to split
(c) getopt ()
the code into separate parts.
(d) none of these [Ans. (c) getopt ()]
.s

(a) Procedural programming


16. ____ command of ‘os’ module executes the exe
(b) Structural programming file to get the desired output.
(c) Object Oriented Programming (a) Main () (b) Name ()
w

(d) Modular Programming (c) Run () (d) System ()


 [Ans. (d) System ()]
 [Ans. (d) Modular Programming]
w

17. The command to clear the window screen is___


10. _______ refers to a file containing python (a) Cls (b) Clear
statements and definitions? (c) Clr (d) Clrscr
w

(a) Procedures  [Ans. (a) Cls]

(b) Modules 18. The keyword used to import the module is_____
(a) Include (b) Input
(c) Structures
(c) Import (d) None of these
(d) Objects [Ans. (b) Modules]
 [Ans. (c) Import]

214
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose the incorrect statement 5. How will you execute C++ program through
python using MinGW interface? Give example.

Importing C++ Programs in Python


1. (i) C ++ program needs to be compiled before
running. Ans. Executing C++ Program through Python

(ii) Python need to be compile(d) (i) Double click the run terminal of MinGW
(iii) Perl, Ruby, ASP are the scripting languages. (ii) Go to the folder where the Python software

m
(iv) Python is not high-level general purpose is located (Python.exe) is located.
programming language. For example here “Python” is located in
(a) i and ii

co
6. What does cd command refers?
(b) ii and iii
Ans. The "cd" command refers to changes directory and
(c) ii and iv absolute path refers to the complete path where
(d) i, ii and iv [Ans. (c) ii and iv] Python is installed.

s.
Very Short Answers 2 MARKS 7. Write a note on
(i) CD command
1. Differentiate static typed language and
(ii) Cls command

ok
dynamic typed language.
Ans. (i)  D command : The "cd" command refers to
C
Ans. (i) A static typed language like C++ requires
the programmer to explicitly tell the changes directory and absolute path refers to
the complete path where Python is installed.
computer what “data type” each data value
o
is going to use. (ii) Cls command : To clear the screen in
command window use cls command
(ii) A dynamic typed language like Python,
ab

doesn’t require the data type to be given 8. What is meant by module?


explicitly for the data. Python manipulate Ans. (i) Modular programming is a software design
the variable based on the type of value. technique to split your code into separate
parts.
2. List some scripting language.
ur

(ii) These parts are called modules. The focus


Ans. The most widely used scripting languages are for this separation should have modules
JavaScript, VBScript, PHP, Perl, Python, Ruby, with no or just few dependencies upon
ASP and Tcl. other modules.
.s

3. What is garbage collection in python? 9. Write a note on main (sys.argv [1]).


Ans. (i) Python deletes unwanted objects (built-in Ans. main(sys.argv[1]) : Accepts the program file
w

types or class instances) automatically to (Python program) and the input file (C++ file)
as a list(array). argv[0] contains the Python
free the memory space.
program which is need not to be passed because
(ii) The process by which Python periodically
w

by default __main__ contains source code


frees and reclaims blocks of memory that reference and argv[1] contains the name of the
no longer are in use is called Garbage C++ file which is to be processed.
w

Collection.
10. Write the syntax and example of
4. What is the use of GNU C complier? (i) os.system () (ii) getopt ()
Ans. g++ is a program that calls GCC (GNU C Ans. (i) os.system (‘g++’ + <varaiable_name1>
Compiler) and automatically links the required  ‘-<mode>’ + <variable_name2>
C++ library files to the object code. (ii) <opts>,<args>=getopt.getopt(argv, options,
[long_options])

215
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


11. Write a command for wrapping C++ code. 4. Write an algorithm for executing C++ program
Unit V - Chapter 14

Ans. if __name__=='__main__': pali_cpp.cpp using python program.pali.py.


main(sys.argv[1:]) Ans. Step 1 : Type the C++ program to check whether
the input number is palindrome or not
Short Answers 3 MARKS in notepad and save it as “pali_cpp.cpp”.

m
Step 2 : Type the Python program and save it
1. Write a note on (i) sys module (ii) OS module
as pali.py
(iii) getopt module
Step 3 : Click the Run Terminal and open the
Ans. (i) sys module provides access to some command window

co
variables used by the interpreter and to
Step 4 : Go to the folder of Python using cd
functions that interact with the interpreter command
(ii) OS module in Python provides a way Step 5 : Type the command Python pali.py -i
of using operating system dependent pali_cpp

s.
functionality
Long Answers 5 MARKS
(iii) The getopt module of Python helps you to
1. Explain the commands for wrapping C++
parse (split) command-line options and
code.

ok
arguments.
Ans. commands for wrapping C++ code :
2. List the commonly used python interfaces. if__name__=='__main__':
Ans. The commonly used interfaces are main(sys.argv[1:])
__name__ (A Special variable) in Python :
o
(i) Python-C-API (API-Application
Programming Interface for interfacing (i) Since there is no main() function in
with C programs) Python, when the command to run a
ab

Python program is given to the interpreter,


(ii) Ctypes (for interfacing with c programs)
the code that is at level 0 indentation is to
(iii) SWIG (Simplified Wrapper Interface be executed.
Generator- Both C and C++) (ii) However, before doing that, interpreter will
ur

(iv) Cython (Cython is both a Python-like define a few special variables. __name__ is
language for writing C-extensions) one such special variable which by default
stores the name of the file. If the source
(v) Boost. Python (a framework for interfacing
file is executed as the main program, the
Python and C++)
.s

interpreter sets the __name__ variable to


(vi) MinGW (Minimalist GNU for Windows) have a value as “__main__”.
(iii) __name__ is a built-in variable which
3. How to import modules in python?
evaluates to the name of the current module.
w

Ans. (i) We can import the definitions inside a Thus it can be used to check whether the
module to another module. We use the current script is being run on its own.
import keyword to do this. (iv) For example consider the following :
w

(ii) Using the module name we can access if __name__ == '__main__':


the functions defined inside the module. main (sys.argv[1:])
The dot (.) operator is used to access the (v) if the command line Python program itself
w

functions. The syntax for accessing the is going to execute first, then __main__
functions from the module is contains the name of that Python program
and the Python special variable __name__
<module name> . <function name>
also contain the Python program name.
(iii) Example : >>> factorial.fact(5) (vi) If the condition is true it calls the main
which is passed with C++ file as argument.

216
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


2. Write a python program to execute the // Save this file as pali_cpp.cpp
following C++ program.

Importing C++ Programs in Python


#Now select File→New in Notepad and type the
/*. To check whether the number is  Python program
palindrome or not using while loop.*/ # Save the File as pali.py . Program that compiles
Ans. //Now select File->New in Notepad and type the  and executes a .cpp file

m
 C++ program # Python c:\pyprg\pali.py -i c:\pyprg\pali_cpp
#include <iostream> import sys, os, getopt
using namespace std; def main(argv):

co
int main() cpp_file = ''
{ exe_file = ''
int n, num, digit, rev = 0; opts, args = getopt.getopt(argv, "i:",['ifile='])
cout<< "Enter a positive number: "; for o, a in opts:

s.
cin>>num; if o in ("-i", "--ifile"):
n = num; cpp_file = a + '.cpp'
while(num) exe_file = a + '.exe'

ok
{ digit = num % 10; run(cpp_file, exe_file)
rev = (rev * 10) + digit; def run(cpp_file, exe_file):
num = num / 10; } print("Compiling " + cpp_file)
cout<< " The reverse of the number is: " << rev
o
os.system('g++'+cpp_file + ' -o ' + exe_file)
<<endl; print("Running " + exe_file)
if (n == rev)
ab

print("-----------------------")
cout<< " The number is a palindrome"; print
else os.system(exe_file)
cout<< " The number is not a print
palindrome";
ur

if __name__ =='__main__': #program


return 0;  starts executing from here
} main(sys.argv[1:])
.s
w


w
w

217
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

  
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net



Chapter DATA MANIPULATION
15 THROUGH SQL

m

co
CHAPTER SNAPSHOT

s.
15.1 Introduction
15.2 SQLite
15.3 Creating a Database using SQLite

ok
15.3.1 Creating a Table
15.3.2 Adding Records
15.4 SQL Query Using Python
15.4.1 SELECT Query
o
15.4.2 CLAUSES IN SQL
15.5 The SQL AND, OR and NOT Operators
ab

15.6 Querying A Date Column


15.7 Aggregate Functions
15.7.1 COUNT ()function
15.7.2 AVG ()
ur

15.7.3 SUM ()
15.7.4 MAX () And MINI () Functions
15.8 Updating A Record
.s

15.9 Deletion Operation


15.10 Data input by User
15.11 Using Multiple Table for Querying
w

15.12 Integrating Query With Csv File


15.13 Table List
w
w

[218]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science

Evaluation 8. Which of the following is called the master


table? [PTA-6]

Data manipulation through SQL


(a) sqlite_master
Part - I \(b) sql_master
Choose the best answer  (1 mark) (c) main_master

m
1. Which of the following is an organized (d) master_main [Ans. (a) sqlite_master]
collection of data? 9. The most commonly used statement in SQL is
(a) Database (b) DBMS (a) cursor (b) select [HY-2019]

co
(c) Information (d) Records
(c) execute (d) commit
 [Ans. (a) Database]
 [Ans. (b) select]
2. SQLite falls under which database system?
10. Which of the following clause avoid the
(a) Flat file database system duplicate? [PTA-5]

s.
(b) Relational Database system
(a) Distinct (b) Remove
(c) Hierarchical database system
(c) Where (d) GroupBy
(d) Object oriented Database system

ok
 [Ans. (a) Distinct
 [Ans. (b) Relational Database system]
3. Which of the following is a control structure
Part - II
used to traverse and fetch the records of the Answer the following questions
database? [PTA-4]  (2 marks)
o
(a) Pointer (b) Key
(c) Cursor (d) Insertion point 1. Mention the users who use the Database.
ab

 [Ans. (c) Cursor] Ans. Users of database can be human users, other
programs or applications.
4. Any changes made in the values of the record
should be saved by the command 2. Which method is used to connect a database?
(a) Save (b) Save As Give an example.
ur

(c) Commit (d) Oblige Ans. Create a connection using connect () method
 [Ans. (c) Commit] and pass the name of the database File.
5. Which of the following executes the SQL Example :
.s

command to perform some action? import sqlite3


(a) execute() (b) key() # connecting to the database
(c) cursor() (d) run()
connection = sqlite3.connect("Academy.db")
w

 [Ans. (a) execute()]


# cursor
6. Which of the following function retrieves the cursor = connection.cursor()
average of a selected column of rows in a table?
w

(a) Add() (b) SUM() 3. What is the advantage of declaring a column


(c) AVG() (d) AVERAGE() as "INTEGER PRIMARY KEY"?
 [Ans. (c) AVG()] Ans. If a column of a table is declared to be an
w

7. The function that returns the largest value of INTEGER PRIMARY KEY, then whenever a
the selected column is NULL is used as an input for this column, the
(a) MAX() (b) LARGE() NULL will be automatically converted into an
(c) HIGH() (d) MAXIMUM() integer which will be one larger than the highest
 [Ans. (a) MAX()] value so far used in that column.
If the table is empty, the value 1 will be used.

219
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. Write the command to populate record in a 3. What is the use of Where Clause?. Give a
Unit V - Chapter 15

table. Give an example. python statement using the where clause.


Ans. To populate (add record) the table "INSERT"  [Govt. MQP-2019]
command is passed to SQLite. "execute" method Ans. The WHERE clause is used to extract only those
executes the SQL command to perform some records that fulfill a specified condition.
Example : To display the different grades scored

m
action.
Example : by male students from "student table"
 sql_command = """INSERT INTO Student import sqlite3
(Rollno, Sname, Grade, gender, Average, birth_ connection = sqlite3.connect("Academy.db")

co
cursor = connection.cursor()
date) VALUES (NULL, "Akshay", "B", "M",
cursor.execute("SELECT DISTINCT(Grade)
"87.8", "2001-12-12");"""""" cursor.execute(sql_
 FROM student where gender='M'")
command)
result = cursor.fetchall()
5. Which method is used to fetch all rows from pring(*result,sep="\")

s.
the database table? OUTPUT:
Ans. The fetchall() method is used to fetch all rows ('B',)
from the database table. ('A',)
('C',)

ok
Example : result = cursor.fetchall()
('D',)
Part - III
4. Read the following details.Based on that write
Answer the following questions a python script to display departmentwise
 (3 marks) records [PTA-5, 6]
o
1. What is SQLite? What is it advantage? database name : organization.db
 [PTA-1; HY-2019] Table name : Employee
ab

Ans. (i) SQLite is a simple relational database Columns in the table : Eno, EmpName,
system, which saves its data in regular data Esal, Dept
files or even in the internal memory of the Ans. import sqlite3
computer. connection = sqlite3. connect ("organization.db")
(ii) It is designed to be embedded in cursor = connection . cursor ()
ur

applications, instead of using a separate cursor. execute ("SELECT * FROM Employee


database server program such as MySQLor  GROUPBY Dept")
Oracle. for row in c:
(iii) SQLite is fast, rigorously tested, and print(row)
.s

flexible, making it easier to work. Python conn.close()


has a native library for SQLite.
5. Read the following details. Based on that write
2. Mention the difference between fetchone() a python script to display records in desending
w

and fetchmany(). [PTA-4] order of


Ans. Eno
database name : organization.db
fetchone() fetchmany()
w

Table name : Employee


(i) The fetchone() method The fetchmany() Columns in the table : Eno, EmpName,
returns the next row method returns Esal, Dept
of a query result set or the next number
w

Ans. import sqlite3


None in case there is no of rows (n) of the
connection = sqlite3 . connect ("organization.db")
row left result set.
cursor = connection . cursor ()
(ii) Using while loop and Displaying specified cursor. execute ("SELECT * FROM Employee
fetchone() method number of records  ORDER BY Eno DESC")
we can display all the is done by using result = cursor . fetchall ()
records from a table. fetchmany(). print (result)

220
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Part - IV 2. Write the Python script to display all the records
of the following table using fetchmany()
Answer the following questions

Data manipulation through SQL


 (5 marks) Icode Item Name Rate
1. Write in brief about SQLite and the steps used 1003 Scanner 10500
to use it. 1004 Speaker 3000

m
Ans. (i) SQLite is a simple relational database 1005 Printer 8000
system, which saves its data in regular data 1008 Monitor 15000
files or even in the internal memory of the
1010 Mouse 700

co
computer.
(ii) It is designed to be embedded in Ans. A
 ssume database name, is shop.db and table
applications, instead of using a separate name is electronics for the given table.
database server program such as MySQLor Python Script :
Oracle. import sqlite3

s.
Advantages : connection = sqlite3.connect ("shop.db")
(i) SQLite is fast, rigorously tested, and cursor = connection . cursor ()
flexible, making it easier to work. Python cusrsor . execute ("SELECT * FROM

ok
has a native library for SQLite. electronics")
To use SQLite, result = cursor . fetchall ()
print (* result, sep = "\n")
Step 1 : import sqlite3
Output :
Step 2 : create a connection using connect
Displaying All the Records
() method and pass the name of
o
(1003, 'Scanner', 10500)
the database file
(1004, 'Speaker', 3000)
Step 3 : Set the cursor object cursor =
ab

(1005, 'Printer', 8000)


connection. cursor ()
(1008, 'Monitor', 15000)
(ii)  Connecting to a database in step2 means
(1010, 'Mouse', 700)
passing the name of the database to be
3. What is the use of HAVING clause? Give an
accessed. If the database already exists the
example python script. [PTA-5]
ur

connection will open the same. Otherwise,


Ans. HAVING clause is used to filter data based on
Python will open a new database file with the group functions. This is similar to WHERE
the specified name. condition but can be used only with group
(iii) Cursor in step 3 is a control structure used functions. Group functions cannot be used in
.s

to traverse and fetch the records of the WHERE Clause but can be used in HAVING
database. clause.
(iv)  Cursor has a major role in working with Example :
Python. All the commands will be executed
w

import sqlite3
using cursor object only. connection = sqlite3.connect("Academy.db")
(v) To create a table in the database, create an cursor = connection.cursor()
object and write the SQL command in it. cursor.execute("SELECT
w

Example : sql_comm = "SQL statement" GENDER,COUNT(GENDER) FROM Student


(vi) For executing the command use the cursor  GROUP BY GENDER HAVING
method and pass the required sql command COUNT(GENDER)>3")
w

as a parameter. Many number of commands result = cursor.fetchall()


can be stored in the sql_comm and can be co = [i[0] for i in cursor.description]
executed one after other. print(co)
(vii) Any changes made in the values of the print(result)
record should be saved by the commend Output :
"Commit" before closing the "Table ['gender', 'COUNT(GENDER)']
connection". [('M', 5)]

221
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. Write a Python script to create a table called Ans. (i) import sqlite3
ITEM with following specification.
Unit V - Chapter 15

connection = sqlite3.connect("ABC.db")
Add one record to the table. cursor.execute("SELECT Supplier.Name,
Name of the database : ABC Supplier.City,Item.ItemName FROM
Name of the table : Item Supplier,Item WHERE Supplier.Icode=
Column name and specification : Item.Icode AND Supplir.City NOT In

m
Delhi")
Icode : integer and act as primary key
s = [i[0] for I in cursor.
Item Name : Character with length 25 description]

co
Rate : Integer print(s)
Record to : 1008, Monitor,15000 result = cursor.fetchall()
be added for r in result:
print r
Ans. import sqlite3 Output :

s.
connection = sqlite3 . connect ("ABc.db") ['Name', 'City', 'ItemName']
cursor = connection . cursor () ['Anu', 'Bangalore', 'Scanner']
sql_command = " " " CREATE TABLE Item ['Shahid', 'Bangalore', 'Speaker']
['Akila', 'Hydrabad', 'Printer']

ok
(Icode INTEGER, Item_
Name VARCHAR (25), Rate ['Girish', 'Hydrabad', 'Monitor']
Integer); " " " cursor.execute ['Shylaja', 'Chennai', 'Mouse']
(sql_command) ['Lavanya', 'Mumbai', 'CPU']
(ii) import sqlite3
sql_command = " " "INSERT INTO Item (Icode,
connection = sqlite3.connect("ABC.db")
o
 Item_name, Rate) cursor.execute("UPDATE Supplier ST
VALUES (1008, "Monitor", 15000); " " " SuppQty = SuppQty + 40 WHERE Name =
ab

cursor.execute (sql_command)  'Akila' ")


connection.commit () cursor.commit()
connection.close () result = cursor.fetchall()
print (result)
print ("TABLE CREATED")
connection.close()
Output :
ur

OUTPUT :
TABLE CREATED
(S004, 'Akila', 'Hydrabad', 1005, 235)
5. Consider the following table Supplier and
item .Write a python script for (i) to (ii) Hands on Experience
.s

SUPPLIER 1. Create an interactive program to accept the


details from user and store in a csv file using
Suppno Name City Icode SuppQty Python for the following table.
w

S001 Prasad Delhi 1008 100 Database name; - DBI


S002 Anu Bangalore 1010 200 Table name : Customer
Cust Cust Address Phone City
w

S003 Shahid Bangalore 1008 175


_Id _Name _no
S004 Akila Hydrabad 1005 195
C008 Sandeep 14/1 41206819 Delhi
S005 Girish Hydrabad 1003 25 Pritam
w

Pura
S006 Shylaja Chennai 1008 180
C010 Anurag 15A, Park 61281921 Kolkata
S007 Lavanya Mumbai 1005 325 Basu Road
(i)  Display Name, City and Itemname of C012 Hrithik 7/2 26121949 Delhi
suppliers who do not reside in Delhi. Vasant
(ii) Increment the SuppQty of Akila by 40. Nagar

222
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Ans. import sqlite3 Output :
import io Enter 3 customer details :

Data manipulation through SQL


import csv Enter 3 customer Id:
d = open('c:/pyprg/sql.csv', 'w') C008
c = csv.writer(d)
C010
connection = sqlite3.connect("dbl.db")

m
cursor = connection. cursor() C012
cursor.execute("create table customer(cust_Id, Enter customer names:
 cust_name, Address, Phone_no, City)") Sandeep

co
print("Enter 3 customer details: ") Anurag Basu
print("Enter 3 customer Id: ")
Hrithik
cid = [int(input() for i in range (3)]
print("Enter customer names: ") Enter their Address:
cname = [input() for i in range (3)] 14/1 Pritam Pura

s.
print("Enter their Address: ") 15A, Park Road
add = [input() for i in range (3)] 7/2 Vasant Nagar
int("Enter their phone numbers: ")
Enter their Phone Numbers:
ph = [int(input()) for i in range (3)]

ok
print("Enter their cities: ") 41206819
city = [input() for i in range (3)] 61281921
n = len(cname) 26121949
for i in range (n): Enter their cities:
o
cursor.execute("insert into customer values
(?,?,?,?,?)", (cid[i], cname[i], add[i], ph[i], Delhi
city[i])) Kolkata
ab

cursor.execute("Select * from customer") Delhi


co = [i[0] for i in cursor.description] Displaying Data :
c.writerow(co) ('cust_Id;, 'cust_Name', 'Address', 'Phone_no',
data = cursor.fetchall()
'city')
for item in data:
ur

c.writerow(item) (C008, 'Sandeep', '14/1 Pritampura', '41206819',


d.close() 'Delhi')
with open('c:/pyprg/sql.csv', "r", newline = (C010, 'Anurag Basu', '15A, Park Road',
 None) as fd:
.s

 '61281921', 'Kolkata')
for line in fd: (C012, 'Hrithik', '7/2 Vasant Nagar', '26121949',
line = line.replace("\n", " ") 'Delhi')
print(line)
w

cursor.ckise()
connection.close()
2. Consider the following table GAMES. Write a python program to display the records for question (i)
w

to (iv) and give outputs for SQL queries (v) to (viii) Table: GAMES
Code Name Game Name Number Prize Money Schedule Date
w

101 Padmaja Carom Board 2 5000 01-23-2014


102 Vidhya Badminton 2 12000 12-12-2013
103 Guru Table Tennis 4 8000 02-14-2014
105 Keerthana Carom Board 2 9000 01-01-2014
108 Krishna Table Tennis 4 25000 03-19-2014

223
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


(i) To display the name of all Games with (iii) To dispaly the name and gamename of
Unit V - Chapter 15

their Gcodes in descending order of their the Players in the ascending order of
schedule date. Gamename,
(ii) To display details of those games which import sqlite3
are having Prize Money more than 7000. conn = sqlite3.connect("Games.db")
(iii) To display the name and gamename of cursor = conn. cursor()

m
the Players in the ascending order of cursor. execute("Select Name, GameName from
Gamename. games order by GameName")
result = cursor. fetchall()
(iv) To display sum of PrizeMoney for each

co
of the Numberof participation groupings print(*result, sep = "\n")
(as shown in column Number 4) conn.close()
Output :
(v) Display all the records based on
('Vidhya', Badminton')
GameName
('Padmaja', 'Carom Board')

s.
Ans. (i) To display the name of all Games with ("Keerthana', 'Carom Board')
their Gcodes in descending order of their ('Guru', 'Table Tennis')
schedule data. ('Krishna', 'Table Tennis')
import sqlite3

ok
(iv)  To display sum of PrizeMoney for each of
conn = sqlite3.connect("Games.db") the Number of participation groupings (as
cursor = conn.cursor() shown in column Number 4)
cursor.execute("Select GameName, Gcode from import sqlite3
 Games order by ScheduleData Desc")
conn = squlite3.connect("Games.db")
result = cursor,fetchal()
o
cursor = conn.cursor()
print(*result, sep = "\n")
cursor.execute("Select 
con.close()
 Sum(Number*Prizemoney)from games")
ab

Output :
 result = cursor.fetchall()
('Table Tennis', 108)
print(result)
('Table Tennis', 103)
conn.close()
('Carom Board', 101)
Output :
('Carom Board', 105)
ur

[(184000)]
('Badminton', 102)
(v)  Display all the records based on
(ii) To display details of those gamnes which
GameName
are having Prize Money more than 7000.
import squlite3
import sqlite3
.s

conn = squlite3.connect("Games.db")
conn = sqlit3.connect("Games.db")
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute("Select * from Games where cursor.execute("Select*from games group by
gamename")
w

 prize money > 7000")


result = cursor.fetchall()
resul = cursor.fetchall()
print(*result, sep = "\n")
print(*result, sep = "\n")
conn.close()
w

conn.close() Output :
Output : ('Carom Board', 101, 'Padmaja', 2, 5000, '01-23-
(102, 'Vidhya', 'Badminton', 2, 12000, '12-12- 2014')
2013')
w

('Carom Board', 105, 'Keerthana', 2, 9000, '01-


(103, 'Guru', 'Table Tennis', 4, 8000, '02-14- 01-2014')
2014') ('Badminton', 102, 'Vidhya', 2, 12000, '12-12-
(105, 'Keerthana', 'Carom Board', 2, 9000, '01- 2013')
01-2014') ('Table Tennis', 103, 'Guru', 4, 8000, '02-14-2014')
(108, 'Krishna', 'Table Tennis', 4, 25000, '03-19- ('Table Tennis', 108, 'Krishna', 4, 25000, '03-19-
2004') 2014')

224
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Example : In this example we are going to
PTA Questions and Answers count the number of records(rows)

Data manipulation through SQL


1 MARK import sqlite3
connection = sqlite3.connect("Academy.db")
1. Which method uses the SQL command to get cursor = connection.cursor()
all the data from the table? [PTA-2] cursor.execute("SELECT COUNT(*) FROM

m
(a) get (b) select  student ")
(c) execute (d) Query result = cursor.fetchall()
 [Ans. (c) execute] print(result)

co
Output:
5 MARKS [(7,)]
1. Write a Python code to display all the records (ii) AVG() :
of the following table using fetchmany(). The following SQL statement in the python
 [PTA-1] program finds the average mark of all students.

s.
Example :
Reg.No Name Marks import sqlite3
3001 Chithirai 353 connection = sqlite3.connect("Academy.db")

ok
3002 Vaigasi 411 cursor = connection.cursor()
3003 Aani 374 cursor.execute("SELECT AVG(AVERAGE)
 FROM student ")
3004 Aadi 289
result = cursor.fetchall()
3005 Aavani 507 print(result)
o
3006 Purattasi 521 Output :
Ans. Assume database name, is month.db and table [(84.65714285714286,)]
ab

name for the given table. (iii) SUM():


Python Script : The following SQL statement in the python
program finds the sum of all average in the
import sqlite3
Average field of “Student table”.
correction=sqlite3.connect("month.db") Example :
ur

cursor=connection.cursor() import sqlite3


cursor.execute("SELECT*FROM Tamil connection = sqlite3.connect("Academy.db")
Months") cursor = connection.cursor()
result=cursor.fetchal() cursor.execute("SELECT SUM(AVERAGE)
.s

 FROM student ")


print(*result, sep="/n") result = cursor.fetchall()
2. Write a note on aggregate functions of SQL. print(result)
w

 [PTA-6] Output :
[(592.6,)]
Ans. These functions are used to do operations from
(iv) MAX() AND MIN() FUNCTIONS :
the values of the column and a single value is
(a) The MAX() function returns the largest
w

returned. value of the selected column.


(i) COUNT() (ii) AVG() (b) The MIN() function returns the smallest
(iii) SUM() (iv) MAX() value of the selected column.
w

(v) MIN() (c) The following example show the highest


(i) COUNT() function : and least average student’s name.
Example :
The SQL COUNT() function returns the number
import sqlite3
of rows in a table satisfying the criteria specified connection = sqlite3.connect("Organization.
in the WHERE clause. COUNT() returns 0 if db")
there were no matching rows. cursor = connection.cursor()

225
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


print("Displaying the name of the Highest 2. Which method is SQlite is used create a
Unit V - Chapter 15

Average") connection with a database file created?


cursor.execute("SELECT  (a) cursor () (b) lite ()
 sname,max(AVERAGE) FROM student ") (c) connect () (d) connection ()
result = cursor.fetchall()  [Ans. (c) connect ()]
print(result)

m
print("Displaying the name of the Least 3. Which method has a major role in working
Average") with python?
cursor.execute("SELECT  (a) cursor ()
 sname,min(AVERAGE) FROM student ") (b) connect ()

co
result = cursor.fetchall() (c) execute ()
print(result) (d) close
Output :  [Ans. (a) cursor ()]
Displaying the name of the Highest Average 4. The SQlite command opens the already created

s.
[('PRIYA', 98.6)] database is
Displaying the name of the Least Average (a) Cursor (b) Sql-comm
[('TARUN', 62.3)] (c) Connect (d) Connection
 [Ans. (c) Connect]

ok
Government Exam Questions and Answers
5. Which of the following is a command to
1 MARK open the already created database from
the statement connection = sqlite3.connect
1. Which is not a SQL clause? [Govt. MQP-2019] ("ABC.db")
o
(a) GROUP BY (a) ABC.db (b) connect
(b) ORDER BY (c) SQlite3 (d) connection
ab

(c) HAVING  [Ans. (b) connect]


(d) CONDITION[Ans. (d) CONDITION] 6. Which of the following is used define a SQL
3 MARKS command in SQlite3?
(a) " " (b) " " " "
1. Write a short note on [Govt. MQP-2019]
ur

(c) ' ' (d) " " " " " "
(i) fetchall() (ii) fetchone()  [Ans. (d) " " " " " "]
(iii) fetchmany
Ans. (i) cursor.fetchall() - fetchall () method is to
7. A table column will be automatically auto
incremented in SQlite3 by giving
.s

fetch all rows from the database table


(a) KEY
(ii) cursor.fetchone() - The fetchone () method
(b) PRIMARY KEY
returns the next row of a query result set or
(c) PRIMARY COLUMN
w

None in case there is no row left.


(d) KEY PRIMARY
(iii) cursor.fetchmany() method that returns  [Ans. (c) PRIMARY COLUMN]
the next number of rows (n) of the result set
8. The command to populate the table is
w

additional questions and Answers (a) ADD (b) APPEND


(c) INSERT (d) ADDROW
Choose the Correct Answer 1 MARK  [Ans. (c) INSERT]
w

1. Which of following is fast, flexible and easy to 9. Which of the following statement in SQL is
work? used to retrieve or fetch data from a table in
a database?
(a) CSV (b) SQlite
(a) select (b) inset
(c) Perl (d) Ruby
(c) create (d) fetch
 [Ans. (b) SQlite]  [Ans. (a) select]

226
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


10. Which sqlite method is used to fetch all rows 19. In which class the group functions can be
from the database table? used?

Data manipulation through SQL


(a) fetch () (b) fetchrowsAll () (a) WHERE (b) HAVING
(c) fectchmany () (d) fetchall () (c) DISTINCT (d) GROUP BY
 [Ans. (d) fetchall ()]  [Ans. (b) HAVING]

m
11. Which SQlite method is used to fetch the 20. The WHERE clause cannot be combined with
required number of rows in the database table?
(a) AND (b) OR
(a) fetch () (b) fetchamany ()
(c) XOR (d) NOT
(c) fetchrows () (d) tablerows ()

co
 [Ans. (b) fetchamany ()]  [Ans. (c) XOR]

12. Which of the following clause will not work in 21. Which of the following operator cannot be
SQlite? used to filter records based on more than one
(a) DISTINCT (b) HAVING condition?

s.
(c) FETCHALL (d) WHERE (a) AND (b) OR
 [Ans. (c) FETCHALL] (c) XOR (d) NOT
 [Ans. (d) NOT]
13. Which SQlite keyword is used to fetch only the

ok
unique values from the database table? 22. Which values cannot be counted?
(a) UNIQUE (b) DISTINCT (a) Integer (b) String
(c) GROUPBY (d) HAVING (c) Float (d) Null
 [Ans. (b) DISTINCT]  [Ans. (d) Null]
o
14. Which SQlite keyword is used to extract only 23. The command to modify the values in the
existing table
those records that fulfill a specified condition?
ab

(a) MODIFY (b) SELECT


(a) WHERE (b) EXTRACT
(c) UPDATE (d) CHANGE
(c) CONNECT (d) CURSOR
 [Ans. (a) WHERE]  [Ans. (c) UPDATE]

15. Which of the following clause is often used 24. How many kinds of placeholders the SQlite3
ur

with aggregate functions to group the result? module supports


(a) ORDER BY (b) WHERE (a)
1 (b) 2 (c) 3 (d) 5
(c) GROUP BY (d) DISTINCT  [Ans. (b) 2]
 [Ans. (c) GROUP BY] 25. Which of the following placeholders does the
.s

16. Which of the following is not an aggregate SQlite3 module supports?


functions? (a) q mark style (b) named style
(a) SUM (b) COUNT (c) module style (d) a and b
w

(c) MAX (d) POW  [Ans. (a) q mark style]


 [Ans. (d) POW]
26. cursor.description will be stored as a
17. The SQlite clause is used to sort the data in the
w

(a) list (b) set


table is (c) tuple (d) dictionary
(a) SORT (b) ORDER BY [Ans. (c) tuple]
(c) GROUP BY (d) ASC SORT
w

 [Ans. (b) ORDER BY] 27. The table's field names can be displayed using
(a) cursor.connect
18. Which SQlite clause is used to filter data base (b) cursor.execute
on the group functions?
(c) cursor.commit
(a) WHERE (b) HAVING
(d) cursor.description
(c) ORDER (d) FILTER
 [Ans. (b) HAVING]  [Ans. (d) cursor.description]

227
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Choose the odd man out 8. Count () returns ____ if there were no
Unit V - Chapter 15

matching rows.
1. (a) count (b) max
(a) 0 (b) 1
(c) OR (d) SUM [Ans. (c) OR]
(c) NOT NULL (d) NULL
2. (a) AND (b) OR  [Ans. (a) 0]
(c) MAX (d) NOT [Ans. (c) MAX]

m
9. ____ SQlite command contain the details of
3. (a) COUNT (b) NULL each table column headings
(c) AVG (d) SUM (a) cursor.description (b) cursor.connect
 [Ans. (b) NULL] (c) cursor.column (d) cursor.fieldname

co
 [Ans. (a) cursor.description]
Choose and fill in the blanks
1. _____is a software application for the 10. In python, the path of a file can be represented
interaction between users and the databases. as_____________
(a) / or \\ (b) \\ or /

s.
(a) CSV (b) Python
(c) DBMS (d) Sys (c) \ or ? (d) // or ?
 [Ans. (c) DBMS]  [Ans. (a) / or \\]

ok
2. _____ program can interact as a user of a SQL Choose the incorrect pair
database. 1. (a) Group by - Aggregate functions
(a) C++ (b) Python (b) order by - Sortind data
(c) Java (d) C (c) Having - filter data
(d) where - Max, min
o
 [Ans. (b) Python]  [Ans. (d) where - Max, min ]
3. ______ is a simple relational database system.
Choose the incorrect statement
ab

(a) Cython (b) Boost


1. Choose the incorrect statement from the
(c) MySQL (d) SQlite following.
 [Ans. (d) SQlite] (i) Distinct keyword is used to fetch only
4. _______ has a native library of SQlite. unique values from the table.
ur

(a) Python (b) C++ (ii) HAVING Clause in used to extract only those
(c) Java (d) C records that fulfill a specified condition.
 [Ans. (a) Python] (iii) GROUP BY clause groups records into
summary columns
.s

5. All the SQlite commands will be executed


(iv) Group functions cannot be used in WHERE
using ______ object.
clause.
(a) connect (b) cursor
(a) i and ii (b) ii and iv
w

(c) CSV (d) python


 [Ans. (b) cursor] (c) iii, iv and i (d) ii and iii[Ans.
6. ______ method run the SQL command to (d) ii and iii]
perform some action.
w

2. Find the correct answer.


(a) run (b) select (i) count funtions returns the number of rows
(c) execution (d) execute in a table satisfying the criteria.
 [Ans. (d) execute]
w

(ii) count returns 0 if there were no matching


7. ______ function returns the number of rows rows.
in a table satisfying the criteria specified in the (iii) Null values are counted.
where class?
(a) i, ii - True (b) i, iii - True
(a) Distinct (b) Count
(c) i, ii, iii - True (d) i, ii, iii - Fa ls e
(c) Having (d) Counter
 [Ans. (a) i, ii - True]
 [Ans. (b) Count]

228
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Very Short Answers 2 MARKS (ii) The SQlite3 module supports two kinds
of placeholders: question marks? ("qmark

Data manipulation through SQL


1. What is a cursor in SQL and databases? style") and named placeholders :name
Ans. (i) A cursor in SQL and databases is a control ("named style").
structure to traverse over the records in a
database. So it's used for the fetching of the 8. How the cursor object is created?

m
results. Ans. The cursor object is created by calling the
(ii) 
The cursor object is created by calling the
cursor() method of connection. The cursor cursor() method of connection. The cursor is
is used to traverse the records from the used to traverse the records from the result set.

co
result set. 9. How the SQL DISTINCT class is helpful to
2. What is the reason behind defining a SQL you?
command with triple quotes? Ans. The DISTINCT clause is helpful when there is
Ans. The reason behind the triple quotes is sometime need of avoiding the duplicate values present in

s.
the values in the table might contain single or any specific columns/table. When we use distinct
double quotes. keyword only the unique values are fetched.
3. What is master table? 10. List the classes used in the SQL SELECT

ok
Ans. SQlite_master is the master table which holds statement.
the key information about your database tables. Ans. (i) DISTINCT
4. How will you sort the data in a table in an (ii) WHERE
ordered way?
(iii) GROUP BY
o
Ans. (i) The ORDER BY clause can be used along
with the SELECT statement to sort the data (iv) ORDER BY.
ab

of specific fields in an ordered way. (v) HAVING


(ii) It is used to sort the result-set in ascending Short Answers 3 MARKS
or descending order.
1. Explain how the SELECT statement can be
5. What is the use of AND, OR operators combined used along with GROUP BY class.
ur

with WHERE clause? Ans. (i) The SELECT statement can be used along
Ans. (i) The WHERE clause can be combined with with GROUP BY clause.
AND, OR, and NOT operators.
(ii) The GROUP BY clause groups records into
(ii) The AND and OR operators are used to
.s

filter records based on more than one summary rows. It returns one records for
condition. each group.

6. Write a note or cursor. description. (iii) It is often used with aggregate functions
w

(COUNT, MAX, MIN, SUM, AVG)


Ans. cursor. description contains the details of each
to group the result-set by one or more
column headings .It will be stored as a tuple and columns.
w

the first one that is 0(zero) index refers to the


2. Write the sqlite steps to connect the database.
column name. Using this command you can
Ans. Step 1 : Import sqlite3
display the table’s Field names.
Step 2 : Create a connection using connect
w

7. Write the placeholders which supported by () method and pass the name of the
SQlite3 module Execute. database File
Ans. Execute (sql[, parameters]) :
Step 3 : Set the cursor object cursor =
(i) Executes a single SQL statement. The connection. cursor ()
SQL statement may be parametrized (i.e.
placeholders instead of SQL literals).

229
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3. Explain how a connect to be made to a database 5. What is the purpose of using
Unit V - Chapter 15

(Academy through python SQlite3. (i) COUNT ()


(ii) AVG ()
Ans. # Python code to demonstrate table creation and
(iii) SUM ()
 insertions with SQL
(iv) MAX ()
# importing module (v) MIN ().

m
import sqlite3 Ans. (i)  COUNT() function returns the number of
rows in a table.
# connecting to the database (ii)  AVG() function retrieves the average of a

co
connection = sqlite3.connect ("Academy.db") selected column of rows in a table.
(iii) SUM() function retrieves the sum of a
# cursor
selected column of rows in a table.
cursor = connection.cursor() (iv) MAX() function returns the largest value of
the selected column.

s.
4. What is the use of aggregate functions used
(v)  MIN() function returns the smallest value
along with SELECT statement? What are they?
of the selected column.
Ans. Aggregate functions are used to do operations

ok
6. Write a note on SELECT statement in SQL.
from the values of the column and a single value
Ans. (i) "SELECT" is the most commonly used
is returned. statement in SQL.
(i) COUNT() (ii) The SELECT Statement in SQL is used to
retrieve or fetch data from a table in a
(ii) AVG()
o
database.
(iii) SUM() (iii) The syntax for using this statement is
ab

(iv) MAX() "Select * from table_name" and all the


table data can be fetched in an object in the
(v) MIN() form of list of lists.
ur


.s
w
w
w

230
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

 
Chapter DATA VISUALIZATION USING PYPLOT:
16 LINE CHART, PIE CHART AND BAR CHART

m

co
CHAPTER SNAPSHOT
16.1 Data Visualization Definition

s.
16.2 Getting Started
16.3 Special Plot Types

Choose the best answer


Part - I
o Evaluation

(1 mark)
ok
4. Read the following code: Identify the purpose of
this code and choose the right option from the
following.
ab

1. Which is a python package used for 2D


C:\Users\Your Name\AppData\Local Programs\
graphics?
Python\ Python36-32\Scripts>pip list
(a) matplotlib.pyplot (b) matplotlib.pip
(c) matplotlib.numpy (d) matplotlib.plt (a) List installed packages
ur

[Ans. (a) matplotlib.pyplot] (b) list command


2. Identify the package manager for Python (c) Install PIP
packages, or modules. [HY-2019]
(d) packages installed
(a) Matplotlib (b) PIP
.s

(c) plt.show() (d) python package [Ans. (a) List installed packages]
[Ans. (b) PIP] 5. To install matplotlib, the following function will
be typed in your command prompt. What does
w

3. Read the following code: Identify the purpose


of this code and choose the right option from “-U”represents?
the following. Python –m pip install –U pip
w

C : \ Us e r s \ Yo u r N a m e \ A p p D a t a \ L o c a l
(a) downloading pip to the latest version
Programs\Python\Python36-32\Scripts>pip
–version (b) upgrading pip to the latest version
w

(a) Check if PIP is Installed (c) removing pip


(b) Install PIP
(d) upgrading matplotlib to the latest version
(c) Download a Package
(d) Check PIP version [Ans. (b) upgrading pip to the latest version]
[Ans. (d) Check PIP version]

[231]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


6. Observe the output figure. Identify the coding (c)
Unit V - Chapter 16

for obtaining this output. 2.100


2.075
2.050
5.0 2.025

4.5 2.000
1.975
4.0 1.950

3.5 1.925

m
1.900
3.0 2.85 2.90 2.95 3.00 3.05 3.10 3.15
2.5
2.0
1.5

co
1.0
1.0 1.5 2.0 2.5 3.0 (d) 4.0

(a) import matplotlib.pyplot as plt 3.5

some numbers
plt.plot([1,2,3],[4,5,1])
3.0

2.5

plt.show() 2.0

s.
1.5

(b) import matplotlib.pyplot as plt 1.0


0.0 0.0 0.5 1.5 2.0 2.5 3.0

plt.plot([1,2],[4,5])
plt.show()

ok
[Ans. (c) ]
(c) import matplotlib.pyplot as plt 2.100
2.075

plt.plot([2,3],[5,1])
2.050
2.025
2.000

plt.show() 1.975
1.950
1.925

(d) import matplotlib.pyplot as plt


o
1.900
2.85 2.90 2.95 3.00 3.05 3.10 3.15

plt.plot([1,3],[4,1])
8. Which key is used to run the module?
ab

plt.show()
(a)
F6 (b) F4 (c) F3 (d) F5
[Ans. (a) import matplotlib.pyplot as plt
[Ans. (d) F5]
plt.plot([1,2,3],[4,5,1])
plt.show()] 9. Identify the right type of chart using the
following hints.
ur

7. Read the code: Hint 1: This chart is often used to visualize a


(a) import matplotlib.pyplot as plt trend in data over intervals of time.
(b) plt.plot(3,2) (c) plt.show() Hint 2: The line in this type of chart is often
Identify the output for the above coding. drawn chronologically.
.s

Epic Info (a) Line chart (b) Bar chart


(a) 16

14 (c) Pie chart (d) Scatter plot


[Ans. (a) Line chart]
w

12
Y axis

10. Read the statements given below. Identify the


10

8
right option from the following for pie chart.
w

Statement A: To make a pie chart with Matplotlib,


6
5 6 7 8 9 10 11
X axis

we can use the plt.pie() function.


1 info Statement B: The autopct parameter allows us to
(b) 16
display the percentage value using
w

14
12
the Python string formatting.
y axis

10
8 (a) Statement A is correct
2 6
4
(b) Statement B is correct
2
2 3 4 5 6 7
(c) Both the statements are correct
3 x axis
(d) Both the statements are wrong
[Ans. (c) Both the statements are correct]

232
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Part - II 5. Write the difference between the following

Data Visualization Using Pyplot: Line Chart, Pie Chart and Bar Chart
Answer the following questions functions: plt.plot([1,2,3,4]), plt.plot([1,2,3,4],
[1,4,9,16]).
 (2 marks) Ans.
plt.plot([1,2,3,4]) plt.plot([1,2,3,4],
1. Define: Data Visualization. [HY-2019]

m
[1,4,9,16])
Ans. Data Visualization is the graphical representation After installing A single list or array
of information and data. The objective of Data Matplotlib, we will provided to the plot ()
Visualization is to communicate information command, matplotlib

co
begin coding by
visually to users. For this, data visualization assumes it is a sequence of
importing Matplotlib y values, and automatically
uses statistical graphics. Numerical data may using the command: generates the x values for
be encoded using dots, lines, or bars, to visually import matplotlib. you. Since python ranges
communicate a quantitative message. start with 0, the default x

s.
pyplot as plt
vector has the same length
2. List the general types of data visualization. Now you have as y but starts with 0.
Ans. (i) Charts imported Matplotlib Hence the x data are

ok
in your workspace. [0, 1, 2, 3].
(ii) Tables plot() is a versatile
You need to display
(iii) Graphs command, and will take
the plots. Using an arbitrary number of
(iv) Maps Matplotlib from arguments.
(v) Infographics This .plot takes many
o
within a Python
(vi) Dashboards script, you have parameters, but the first
to add plt.show() two here are 'x' and 'y'
ab

3. List the types of Visualizations in Matplotlib. coordinates. This means,


method inside the file you have 4 co-ordinates
Ans. There are many types of Visualizations under
to display your plot. according to these lists:
Matplotlib. Some of them are : (1,1), (2,4), (3,9) and
(i) Line plot (4,16).
ur

(ii) Scatter plot Part - III


(iii) Histogram Answer the following questions
(iv) Box plot
 (3 marks)
.s

(v) Bar chart and


(vi) Pie chart 1. Draw the output for the following data
visualization plot. [Govt. MQP-2019]
w

4. How will you install Matplotlib? import matplotlib.pyplot as plt


Ans. (i) Matpotlib can be installed using pip plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example
software. one")
w

(ii) Pip is a management software for installing plt.bar([2,4,6,8,10],[8,6,2,5,6], 


python packages.  label="Example two", color='g')
(iii) Importing Matplotlib using the command : plt.legend()
w

import matplotlib.pyplot as plt plt.xlabel('bar number')


(iv) Matplotlib can be imported in the plt.ylabel('bar height')
workspace. plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()

233
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Ans. Ans. import matplotlib.pyplot as plt
slices = [7, 2, 2, 13]
Unit V - Chapter 16

activities = ["sleeping", "eating", "working",


 "playing", ]
plt.pie (slices, labels = activities, autopct =
'y.1.1f%%)

m
plt.title ("Interesting Graph Check it out")
plt.show()
Part - IV

co
Answer the following questions
2. Write any three uses of data visualization.  (5 marks)
 [PTA-1, 5; HY-2019] 1. Explain in detail the types of pyplots using
Ans. (i) Data Visualization help users to analyze Matplotlib. [PTA-6]

s.
and interpret the data easily. Ans. Matplotlib allows you to create different kinds of
(ii) It makes complex data understandable and plots ranging from histograms and scatter plots
usable. to bar graphs and bar charts.

ok
(iii) Various Charts in Data Visualization helps
to show relationship in the data for one or Line Chart :
more variables. (i) A Line Chart or Line Graph is a type of
3. Write the coding for the following: chart which displays information as a series
of data points called ‘markers’ connected
o
a. To check if PIP is Installed in your PC.
b.  To Check the version of PIP installed in by straight line segments.
your PC. (ii) A Line Chart is often used to visualize
ab

c. To list the packages in matplotlib. a trend in data over intervals of time – a


Ans. a. To check if PIP is Installed in your PC : time series – thus the line is often drawn
(i) In command prompt type pip – version. chronologically.
(ii) If it is installed already, you will get version. (iii) Example
ur

(iii) Command : Python - m pip install - U pip.


Program for Line plot :
b. To Check the version of PIP installed in
your PC : import matplotlib.pyplot as plt
C:\Users\YourName\AppData\Local\ years = [2014, 2015, 2016, 2017, 2018]
.s

Programs\Python\Python36-32\ total_populations = [8939007, 8954518,


Scripts>pip-version.  8960387, 8956741, 8943721]
c. To list the packages in matplotlib :
plt.plot (years, total_populations)
w

C:\Users\YourName\AppData\Local\
Programs\Python\Python36-32\Scripts> plt.title ("Year vs Population in India")
pip list plt.xlabel ("Year")
w

4. Write the plot for the following pie chart plt.ylabel ("Total Population")
output. plt.show()
In this program,
w

Plt.title() → specifies title to the graph


29.2%

54.2%
Plt.xlabel() → specifies label for X-axis
8.3%
8.3%
Plt.ylabel() → specifies label for Y-axis

234
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Output : Output :

Data Visualization Using Pyplot: Line Chart, Pie Chart and Bar Chart
Year vs Population in India
MARKS
8960000

80
8955000

m
8950000 60

RANGE
8945000
40

co
8940000
20
2014.4 2014.5 2015.0 2015.5 2016.0 2016.6 2017.0 2017.7 2018.0
Year

0
TAMIL ENGLISH MATHS PHYSICS CHEMISTRY CS
Bar Chart :

s.
(i) A BarPlot (or BarChart) is one of the
most common type of plot. It shows the Pie Chart :
relationship between a numerical variable

ok
(i) Pie Chart is probably one of the most
and a categorical variable.
common type of chart. It is a circular
(ii) Bar chart represents categorical data with
rectangular bars. Each bar has a height graphic which is divided into slices to
corresponds to the value it represents. The illustrate numerical proportion.
o
bars can be plotted vertically or horizontally. (ii) The point of a pie chart is to show the
(iii) It’s useful when we want to compare a given relationship of parts out of a whole. To
ab

numeric value on different categories. To


make a Pie Chart with Matplotlib, we can
make a bar chart with Matplotlib, we can
use the plt.pie() function.
use the plt.bar() function.
(iv) Example : (iii) The autopct parameter allows us to display
ur

import matplotlib.pyplot as plt the percentage value using the Python


# Our data string formatting.
labels = ["TAMIL", "ENGLISH", "MATHS", (iv) Example :
.s

 "PHYSICS", "CHEMISTRY", "CS"]


import matplotlib.pyplot as plt
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5]
# Generating the y positions. Later, we'll sizes = [89, 80, 90, 100, 75]
w

 use them to replace them with labels. labels = ["Tamil", "English", "Maths",
y_positions = range (len(labels))  "Science", "Social"]
# Creating our bar plot
w

plt.pie (sizes, labels = labels, autopct =


plt.bar (y_positions, usage) "%.2f ")
plt.xticks (y_positions, labels)
plt.axes().set_aspect ("equal")
w

plt.ylabel ("RANGE")
plt.title ("MARKS") plt.show()

plt.show()

235
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores

 
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Output : 3. Explain the purpose of the following functions:
Unit V - Chapter 16

a. plt.xlabel
b. plt.ylabel
English
c. plt.title
Tamil
d. plt.legend()

m
18.43
20.51
e. plt.show()
Maths 20.74
Ans. a. Specifies label for x-axis
17.28
b. Specifies label for y-axis

co
23.04 Social

c.  Specifies title to the graph or assigns the


Science
plot title.
d. Invoke the default legend with plt
e. Display the plot

s.
2. Explain the various buttons in a matplotlib Hands on Experience
window. [PTA-5]
Ans. Buttons in the output : In the output figure,

ok
1. Create a plot. Set the title, the x and y labels for
you can see few buttons at the bottom left corner. both axes.
Let us see the use of these buttons. Ans. import matplotlib.pyplot as plt
Subplots x = [1, 2, 3]
Home Button Pan Axis Button Button
y = [5, 7, 4]
o
plt.plot(x,y)
plt.xlabel('x-axis')
ab

Save the
Forward / Back Buttons Zoom
Button Figure Button plt.ylabel('y-axis')
(i) Home Button → The Home Button will plt.title('LINE GRAPH')
help one to begun navigating the chart. If plt.show()
LINE GRAPH
you ever want to return back to the original
ur

14
view, you can click on this.
(ii) Forward/Back buttons → These buttons 12
can be used like the Forward and Back
buttons in browser. Click these to move
.s

10
back to the previous point you were at, or
Y - Axis

forward again.
8
(iii) Pan Axis → This cross-looking button
w

allows you to click it, and then click and


6
drag graph around.
(iv) Zoom → The Zoom button lets you click on 4
w

it, then click and drag a square would like 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 3.00
to zoom into specifically. Zooming in will X - Axis

require a left click and drag. Zoom out with


2. Plot a pie chart for your marks in the recent
a right click and drag.
w

examination.
(v) Configure Subplots → This button allows
Ans. Example :
you to configure various spacing options
with figure and plot. import matplotlib.pyplot as pit
sizes = [89, 80, 90, 100, 75]
(vi) Save Figure → This button will allow you to
labels = ["Tamil", "English", "Maths", "Science",
save figure in various forms.
"Social"]

236
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


plt.pie(sizes, labels = labels, autopct = "%.ef ") 4. Plot a bar chart for the number of computer

Data Visualization Using Pyplot: Line Chart, Pie Chart and Bar Chart
plt.axes().set_aspect("equal") science periods in a week.
plt.show() Ans. import matplotlib.pyplot as plt
Output : labels = ["MON", "TUE", "WED", "THUR",
 "FRI", "SAT",]

m
usage = [3, 2, 1, 3, 2, 2]
English y_positions = range (len(labels))
Tamil plt.bar(y_positions, usage)
18.43

co
20.51 plt.xticks(y_positions, labels)
Maths 20.74 plt.ylabel("PERIODS")
17.28 plt.ylabel("years")
23.04 Social plt.title("NO. OF CS PERIODS")
plt.show()

s.
Science
Number of CS Periods

ok
5
3. Plot a line chart on the academic performance
4
of Class 12 students in Computer Science for
PERIODS

the past 10 years. 3


Ans. import matplotlib.pyplot as plt
o
2
years = [2009, 2010, 2011, 2012, 2013, 2014,
1
 2015, 2016, 2017, 2018]
ab

cs = [65, 70, 75, 76, 78, 80, 82, 85, 87, 92] 0
plt.plot(years,cs) MON TUE WED THU FRI SAT
plt.title("COMPUTER SCIENCE ACADEMIC
PERFORMANCE") PTA Questions and Answers
ur

plt.xlabel("cs")
plt.ylabel('years") 1 MARK
plt.show() 1. The most popular data visualization library
.s

COMPUTER SCIENCE ACADEMIC PERFORMANCE which allows creating charts in few line of
code in Python.  [PTA-1]
2018
(a) Matplotlib (b) Infographics
w

2017 (c) Data visualization (d) pip


2016  [Ans. (a) Matplotlib]
2015
2. The function to make a pie chart with
YEAR

2014 Matplotlib:  [PTA-2]


2013 (a) plt.bar() (b) pie.plt()
2012 (c) bar.plt() (d) plt.pie()
w

2011  [Ans. (d) plt.pie()]


2010
3. Which of the following is not a type of
2009 visualization under matplotlib?  [PTA-3]
(a) Histogram (b) Pie chart
60 65 70 75 80 85 90 95 65 (c) Box plot (d) SQLite
CS  [Ans. (d) SQLite]

237
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


4. ______ plot is a type of plot that shows the 3. What is Pip? [PTA-6]
data as a collection of points.
Unit V - Chapter 16

[PTA-4] Ans. Matplotlibinstalled using pip. Pip is a


(a) Line (b) Scatter management software for installing python
(c) Box (d) Pie packages.
 [Ans. (b) Scatter]
3 MARKS

m
5. Which of the following matplotlib function is
used to draw line chart? [PTA-5] 1. What is pie chart? How will you create pie
(a) pie() (b) line() chart in Python? Give an example. [PTA-3]

co
(c) bar() (d) plot() Ans. Pie Chart
 [Ans. (b) line()] (i) Pie Chart is probably one of the most
6. In Line Chart or Line Graph displays common type of chart. It is a circular
information as a series of data points called graphic which is divided into slices to
______.  [PTA-6] illustrate numerical proportion. The point

s.
of a pie chart is to show the relationship of
(a) Markers (b) Points
parts out of a whole.
(c) Dots (d) Lines
(ii)  To make a Pie Chart with Matplotlib,
 [Ans. (a) Markers]

ok
we can use the plt.pie() function. The
2 MARKS autopct parameter allows us to display the
1. What is Matplotlib? [PTA-2] percentage value using the Python string
Ans. Matplotlib is the most popular data visualization formatting.
Example :
o
library in Python. It allows to create charts in
few lines of code. import matplotlib.pyplot as plt
ab

2. Draw the chart for the given Python snippet. sizes = [89, 80, 90, 100, 75]
 [PTA-4] labels = ["Tamil", "English", "Maths", "Science",
import matplotlib.pyplot as plt "Social"]
plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) plt.pie (sizes, labels = labels, autopct = "%.2f ")
ur

plt.show() plt.axes().set_aspect ("equal")


Ans. Program : plt.show()
import matplotlib.pyplot as plt Output :
plt.plot([1,2,3,4])
.s

plt.show()
Output : English
w

18.43 Tamil
20.51
4.0

Maths
w

3.5 20.74

3.0 17.28

2.5 Social
23.04
w

2.0
Science
1.5

1.0
0.0 0.5 1.0 1.5 2.0 2.5 3.0

238
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


5 MARKS Ans.

Data Visualization Using Pyplot: Line Chart, Pie Chart and Bar Chart
LINE GRAPH
1. Draw the output for the following Python 14 Line1
code. [PTA-3] Line2

import matplotlib.pyplot as plt 12


a = [1, 2, 3]

m
b = [5, 7, 4]
10
x = [1, 2, 3]

Y - Axis
y = [10, 14, 12]

co
8
plt.plot(a,b, label='Lable 1')
plt.plot(x,y, label='Lable 2')
plt.xlabel('X-Axis') 6

plt.ylabel('Y-Axis')
plt.legend() 4

s.
plt.show() 1.00 1.25 1.50 1.75 2.00 2.25 2.50 2.75 3.00
X - Axis

ok
2. What are the key differences between Histogram and Bar graph? [PTA-4]
Ans.
Histogram Bar graph
(i) Histogram refers to a graphical A bar graph is a pictorial representation of data
o
representation; that displays data by way of that uses bars to compare different categories
bars to show the frequency of numerical data. of data.
ab

(ii) A histogram represents the frequency Conversely, a bar graph is a diagrammatic


distribution of continuous variables. comparison of discrete variables.
(iii) Histogram presents numerical data. Bar graph shows categorical data.
ur

(iv) I tems of the histogram are numbers, which As opposed to the bar graph, items are
are categorised together, to represent ranges considered as individual entities.
of data.
(v) A histogram, this cannot be done, as they are I n the case of a bar graph, it is quite common
.s

shown in the sequence of classes. to rearrange the blocks, from highest to lowest.
(vo)  e width of rectangular blocks in a
Th The width of the bars in a bar graph is always
histogram may or may not be same same.
w

Government Exam Questions and Answers


w

1 MARK
1. To make a bar chart with Matplotlib, which function should be used? [Govt. MQP-2019]
w

(a) plt.bar() (b) plt.chart()


(c) pip.bar() (d) pip.chart()
[Ans. (a) plt.bar()]

239
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


3 MARKS 5. Which of the following is a collection of
resources assembled to create a single unified
Unit V - Chapter 16

1. Write a Python code to display the following visual display?


chart. [Govt. MQP-2019] (a) Info graphics (b) Dashboard
7 (c) Graphics (d) Chats
 [Ans. (b) Dashboard]

m
6
6. Which of the following translate complex ideas
5 and concepts into a simple visual format?
4 (i) Data visualization (ii) Dashboards

co
3 (iii) Tables (iv) Maps
(a) i, iii (b) iii, ii (c) i, iv (d) i, ii
2
 [Ans. (d) i, ii]
1
7. In Python matplotlib is a

s.
1 2 3 4 5 6 7 8 (a) control structure (b) dictionary
Ans. import matplotlib.pyplot as plt (c) library (d) list
plt.plot([1,2,3,4])  [Ans. (c) library]

ok
plo.show() 8. Matplotlib allows you to create a
Output : (a) Table (b) Charts
 This window is a matplotlib window, which (c) Maps (d) Info graphics
allows you to see your graph. You can hover the  [Ans. (b) Charts]
o
graph and see the coordinates in the bottom 9. How many types of visualizations are there
right. under matplotlib?
ab

(a) 6 (b) 4
additional questions and Answers (c) 5 (d) Many
 [Ans. (d) Many]
Choose the Correct Answer 1 MARK 10. Which of following is not a visualization under
1. Which kind of data encoded visually matplotlib?
ur

communicate a quantitative message? (a) Scatter plot (b) Table plot


(a) String (b) Numbers (c) Histogram (d) Box plot
(c) Images (d) None of these  [Ans. (b) Table plot]
.s

 [Ans. (b) Numbers] 11. Which plot displays the distribution of data
based on the five number summary?
2. The numerical data is encoded using
(a) Scatter plot (b) Line plot
(a) dots (b) lines
w

(c) Box plot (d) Chart plot


(c) bars (d) all of these
 [Ans. (c) Box plot]
 [Ans. (d) all of these]
12. Which of the following is not a five number
w

3. Which of the following is not a type of Data summary in box plot visualization?
Visualization? (a) First Quartile (b) Second Quartile
(a) Graphs (b) Picture (c) Third Quartile (d) Minimum
(c) Maps (d) Infographics
w

 [Ans. (b) Second Quartile]


 [Ans. (b) Picture]
13. Which of the following is a management
4. Which of the following is the representation of software for installing python package?
information in a graphic format?
(a) pip (b) plot
(a) Info graphics (b) Graphics
(c) matplotlib (d) plot lib
(c) Dashboard (d) Charts
 [Ans. (a) Info graphics]  [Ans. (c) matplotlib]

240
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


14. Which of the following command is used to 22. Which type of charts displays information as

Data Visualization Using Pyplot: Line Chart, Pie Chart and Bar Chart
install matplotlib for coding? series of data points?
(a) import plt.matplotlib as plot (a) Bar (b) Pie
(c) Line (d) Histogram
(b) import plot.matplotlib as plt
 [Ans. (c) Line]
(c) import matplotlib.plt as plot 23. A line chart is type of chart which displays on

m
(d) import matplotlib.pyplot as plt formats as a data points called
 [Ans. (d) import matplotlib.pyplot as plt] (a) series (b) markers
15. Which of the following method will be add (c) plot (d) lib

co
 [Ans. (b) markers]
inside the file to display plot?
24. Which type of chart shows the relationship
(a) show () (b) display () between a numerical variable and categorical
(c) execute () (d) plot () variable?
(a) line (b) bar

s.
 [Ans. (a) show ()]
(c) pie (d) x-y plot
16. The default x.vector has the same length of y  [Ans. (b) bar]
but starts with 25. Which refers to a graphical representation

ok
(a) 3 (b) 2 (c) 1 (d) 0 that displays data by way of bars to show the
frequency of numerical data?
 [Ans. (d) 0] (a) Bar chart (b) Barch graph
17. Which of the following command will take an (c) Pie chart (d) Histogram
 [Ans. (d) Histogram]
o
arbitrary number of arguments?
(a) show () (b) plot () 26. Which of the following chart represents
the frequency distribution of continuous
ab

(c) legend () (d) title ()


 [Ans. (b) plot()] variables?
(a) Histogram (b) Pie
18. Which button will help to navigate the chart?
(c) Line (d) Bar
(a) Navigate (b) Pan
 [Ans. (a) Histogram]
(c) Home (d) Zoom
ur

27. Which of the following one indicates


 [Ans. (c) Home] discontinuity?
19. Which button used to click and drag a graph (a) Histogram (b) Pie
around? (c) Bar graph (d) None of these
.s

(a) pan (b) home [Ans. (c) Bar graph]


(c) zoom (d) drag 28. Which of the following plot we cannot
 [Ans. (a) pan] rearrange the blocks from highest to lowest?
w

20. Which button allows to configure various (a) Line (b) Bar chart
spacing options with figure? (c) Pie chart (d) Histogram
(a) configure plots  [Ans. (d) Histogram]
w

29. In which plot the width of the bars is always


(b) configure subplots same?
(c) subplots configure (a) Line (b) Bar chat
w

(d) plots configure (c) Pie chart (d) Histogram


 [Ans. (b) configure subplots]  [Ans. (b) Bar chat]
21. The different kinds of plot created using 30. In which plot the width of the bars may or may
not be same?
(a) Matplotlib (b) Matplot
(a) Histogram (b) Pie chat
(c) Plotlib (d) Matliplot
(c) Bar chat (d) Line
 [Ans. (a) Matplotlib]
 [Ans. (a) Histogram]

241
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample

 
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


31. Which plot is a circular graphical 8. _____ and _____ are the two ways to display
Unit V - Chapter 16

representation of numerical data? data in the form of diagram.


(a) Histogram (b) xy plot
(a) Line chart, Pie chart
(c) Bar plot (d) Pie chart
 [Ans. (d) Pie chart] (b) Line chart, Bar chart

m
(c) Bar Graph, Histogram
32. Which parameter used to display() the
percentage value using Python string (d) Line chart, Histogram
formatting in pie chart?  [Ans. (c) Bar Graph, Histogram]

co
(a) percent (b) autopct
(c) pct (d) percentage
 [Ans. (b) autopct]
Very Short Answers 2 MARKS
Choose and fill in the blanks

s.
1. What is Infographics data visualization?
1. Data visualization used ______ graphics.
(a) 2D (b) 3D Ans. Infographics → An infographic (information
(c) Statistical (d) Image graphic) is the representation of information in

ok
 [Ans. (c) Statistical] a graphic format.
2. ____ is the graphical representation of
2. Write a note on Dashboard.
information and data.
(a) Data visualization (b) Data Graphics Ans. Dashboard → A dashboard is a collection
o
(c) Data Dimension (d) Data Images of resources assembled to create a single
 [Ans. (a) Data visualization] unified visual display. Data visualizations
ab

3. ______ in data visualization helps to show and dashboards translate complex ideas and
relationship in the data for more variables. concepts into a simple visual format. Patterns
(a) Tables (b) Graphics and relationships that are undetectable in text
(c) Charts (d) Dashboards are detectable at a glance using dashboard.
 [Ans. (c) Charts]
ur

4. In Scatter plot, the position of a point depends 3. Which plot shows the data as a collection of
on its __________ value. points? Explain or write a note on scatter plot.
(a) 2 – Dimensional (b) 3 – Dimensional
Ans. Scatter plot : A scatter plot is a type of plot
(c) 1 – Dimensional (d) 7 – Dimensional
.s

 [Ans. (a) 2 – Dimensional] that shows the data as a collection of points.


The position of a point depends on its two-
5. If a list given to the plot () command, matplotlib
assumes it is a sequence of _____ values. dimensional value, where each value is a position
w

(a) x (b) y (c) 0 (d) 4 on either the horizontal or vertical dimension.


 [Ans. (b) y]
4. Write note or Box plot.
6. Zoom in will require ______ and drag.
w

(a) click (b) left click Ans. Box plot : The box plot is a standardized way of
(c) double click (d) right click displaying the distribution of data based on the
 [Ans. (b) left click] five number summary: minimum, first quartile,
w

median, third quartile, and maximum.


7. Zoom out will require ______ and drag.
(a) click 5. What are the two ways to display data in the
(b) left click form of diagram?
(c) double click Ans. Bar Graph and Histogram are the two ways to
(d) right click [Ans. (d) right click] display data in the form of a diagram.

242
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample


for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ XII Std - Computer Science


Short Answers 3 MARKS 2. List the buttons in matlibplot window.

Data Visualization Using Pyplot: Line Chart, Pie Chart and Bar Chart
Ans.
1. Write a python code to display the following
Subplots
plot. Home Button Pan Axis Button Button
Ans. Program :

m
For example, to plot x versus y, you can issue the
command:
import matplotlib.pyplot as plt Forward / Back Buttons Zoom Save the
Button Figure Button
plt.plot([1,2,3,4], [1,4,9,16])

co
plt.show() 3. Read the following code. What does the
Output : following represents.
(i) Labels
(ii) Usage

s.
16 (iii) X ticks
14 (iv) Range
(v) Show

ok
12

10 Ans. (i) Labels → Specifies labels for the bars.


8 (ii)  Usgae → Assign values to the labels
6 specified.
4
(iii) Xticks → Display the tick marks along
o
2
the x-axis at the values represented. Then
1.0 1.5 2.0 2.5 3.0
specify the label for each tick mark.
ab
3.5 4.0

(iv) Range → Create sequence of numbers.


(v) Show → Displays the plot
ur


.s
w
w
w

243
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

12
th Govt. Model Question Paper - 2019-20
STD.
Computer Science
Time : 3.00 Hours] as per Govt. Notifications [Maximum Marks : 70

m
Instructions : 4. Extension of Python files is

(a) Check the question paper for fairness of (a) .Pyt (b) .txt (c) .Pdm (d) .Py

co
printing. If there is any lack of fairness, 5. The output of the Segment
inform the Hall Supervisor Immediately.
for i in range (10, 0, 2)
(b) Only Blue or Black ink must be used to Print(i)

s.
write and underline. Pencil can be used to
is
draw the diagrams.
(a) 10 8 6 4 2 0 (b) 10 8 6 4 2
PART - I

ok
(c) 0 2 4 6 8 10 (d) Error
Note : (i) 
All questions are compulsory.
 [15 × 1 = 15] 6. The bin( ) function returns a binary string
prefixed with:
(ii) 
Choose the most appropriate
o
answer from the given four (a) 0 (b) 1 (c) 0b (d) 1b
alternatives and write the option
7. The positive and negative index values of ‘P’ in
ab

code with the corresponding


the string Str1=’COMPUTER’ are
answer.
(a) 3, –4 (b) 4, –4
1. Bundling two values together into one can be (c) 3, –5 (d) 4, –5
considered as
ur

(a) Pair (b) Triplet 8. Which of the following set operation includes all
the elements that are in two sets but not the one
(c) Single (d) Quadrat
that are common to two sets?
.s

2. The kind of scope of the variable ‘a’ used in the (a) Symmetric difference (b) Difference
pseudo code given below (c) Intersection (d) Union
(A) Disp(): (B) a:=7
w

9. A variable prefixed with double underscore is


(C) print a (D) Disp()
(a) private (b) public
(a) Local (b) Global
w

(c) protected (d) static


(c) Enclosed (d) Built-in
10. The data model developed by IBM is
3. Big Ω is the reverse of
w

(a) Hierarchical (b) Relational


(a) Big O (b) Big Ѳ
(c) Network (d) ER
(c) Big A (d) Big S

[ 244 ]
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

245
Sura’s ➠ 12th Std - Computer Science - Govt. Model Question Paper - 2019

11. The SQL command to make a database as 21. What will be the output of the following snippet?
current active database is alpha=list(range(65, 70))
(a) CURRENT (b) USE for x in alpha:
(c) DATABASE (d) NEW print(chr(x), end=‘\t’

m
12. The expansion of CRLF is 22. What is the use of WHERE clause in SQL?

(a) Control Return and Line Feed 23. What are the steps involved in file operation of
(b) Carriage Return and Form Feed Python?

co
(c) Control Router and Line Feed 24. Distinguish compiler and interpreter.
(d) Carriage Return and Line Feed PART - III
13. The function call statement of the segment. Answer any six questions. Question No. 29 is

s.
if__name__ == ‘__main__’: compulsory. 6 × 3 = 18

main(sys.argv[1:]) 25. Why strlen is called pure function?

ok
is 26. Which strategy is used for program designing?
(a) main(sys.argv[1:]) (b) __name__ Define the strategy.

(c) __main__ (d) argv 27. Which jump statement is used as placeholder?
Why?
o
14. Which is not a SQL clause?
28. What are the points to be noted while defining
(a) GROUP BY (b) ORDER BY a function?
ab

(c) HAVING (d) CONDITION 29. Write a Python program to display the given
pattern
15. To make a bar chart with Matplotlib, which
function should be used? COMPUTER
ur

COMPUTE
(a) plt.bar( ) (b) plt.chart( )
COMPUT
(c) pip.bar( ) (d) pip.chart( )
COMPU
.s

PART - II COMP
Answer any six questions. Question No. 21 is COM
compulsory. 6 × 2 = 12 CO
w

C
16. What do you mean by Namespaces?
30. What is the output of the following program?
w

17. What is searching? Write its types. class Greeting:

18. Define Operator and Operand. def__init__(self, name):


self.__name = name
w

19. What are the types of looping supported by


def display(self):
Python?
print(“Good Morning”, self.__
20. What is the use of the operator + = in Python name)
string operation? obj=Greeting(‘Tamil Nadu’)
obj.display()

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ 12th Std - Computer Science - Govt. Model Question Paper - 2019 246

31. Explain Cartesian product with a suitable 36. (a) Explain about the find( ) function in Python
example. with example.
32. Write a short note on (OR)
(i) fetchall( ) (ii) fetchone( ) (b) C ompare remove( ), pop( ) and clear( )
(iii) fetchmany( ) function in Python.

m
33. Write a Python code to display the following 37. (a) Explain the components of DBMS.
chart. (OR)

co
7 (b) What are the components of SQL? Write the
6 commands in each.
5 38. (a) Explain the following operators in Relational
4
Algebra with suitable example

s.
3
2 (1) Union. ()
1 (2) Intersection ()

ok
1 2 3 4 5 6 7 8 (OR)
PART - IV (b) D raw the output for the following data
Answer all the questions:. 5 × 5 = 25 visualization plot.
34. (a) Write any five benefits in using modular import matplotlib.pyplot as plt
o
programming. plt.bar([2, 4, 6, 8, 10], [5, 2, 7, 8, 2],
(OR)  label=“Example one”)
ab

(b) Explain input( ) and print ( ) functions of plt.bar([1, 3, 5, 7, 9], [8, 6, 2, 5, 6],
Python with example.  lable=“Example two”, color=‘g’)
35. (a) Write a detail note on for loop in Python. plt.legend( )
(OR) plt.xlabel(‘bar number’)
ur

(b) Example the different types of functions in plt.ylabel(‘bar height’)


Python with example. plt.title(‘Epic Graph\nAnother Line’)
.s

plt.show( )


w
w
w

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

12
th
Common Quarterly Examination - 2019
STD.
PART - III Reg. No.

Time : 3.00 Hours] Computer Science [Maximum Marks : 70

m
Instructions :
6. _______ separation is necessary between tokens.

co
(a) Check the question paper for fairness of (a) ; (b) Delimiter
printing. If there is any lack of fairness, (c) White Space (d) :
inform the Hall Supervisor immediately.
(b) Use Blue or Black ink to write and underline 7. Which is optional part in range ( ) function?
and pencil to draw diagrams (a) end (b) step

s.
PART - I (c) stop (d) start
Note : (i) Answer all questions. 8. What is the output of the following program.
 [15 × 1 = 15] c=1

ok
(ii) 
Choose the most appropriate def add ( ):
answer from the given four print (c)
alternatives and write the option add ( )
code and the corresponding
(a) 1 (b) 0 (c) none (d) C
answer.
o
9. Which command deletes the elements and it
1. The Variables in a function definition are called retains list
ab

as (a) remove ( ) (b) del ( )


(a) Subroutines (b) Function (c) Clear ( ) (d) Pop ( )
(c) Definition (d) Parameters 10. What is the output of the function Print
2. The data type whose representation is known (Chr(66))?
ur

are called (a) A (b) C (c) b (d) B


(a) Built-in datatype 11. ________ is the mixed collection of elements.
(b) Derived data type (a) Lists (b) Sets
.s

(c) Concrete data type (c) Dictionary (d) Tuples


(d) Abstract data type 12. Which of the following method is used as
destructor?
w

3. Containers for mapping names of variables to


objects is _______ (a) __dest__( ) (b) __del__( )
(c) __int__( ) (d) __rem__( )
(a) Name Spaces (b) Scope
w

(c) Mapping (d) Binding 13. Which model database created by dividing the
object into entity and its Characteristics into
4. What is another name of Binary search? attributes?
(a) Linear
w

(a) Hierarchical (b) Relational


(b) Half interval (c) Network (d) ER data base
(c) Decimal
14. The Original version of SQL is released in the
(d) Boolean
year.....
5. How many ways python program can be written? (a) 1970 (b) 1980
(a)
2 (b) 4 (c) 3 (d) 1 (c) 1986 (d) 1992

[ 247 ]
orders@surabooks.com Ph: 9600175757 / 8124201000
This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

248
Sura’s ➠ 12th Std - Computer Science - Common Quarterly Examination - 2019

15. Which command saves any transaction in PART - IV


database permanently? Answer all the questions:. 5 × 5 = 25
(a) save (b) save point
34. (a) Explain the selection Sort Algorithm with
(c) commit (d) roll back
an example.

m
PART - II
Answer any 6 questions. Q.No. 24 is compulsory. (OR)
 6 × 2 = 12 (b) Discuss in detail about Tokens in python.

co
16. Define pure function. Give one example. 35. (a) Write a program to check the given character
17. What is List? Give an example. is a vowel or not.

18. What is LEGB rule? (OR)


(b) E xplain various function arguments in

s.
19. Write short notes on floor division operator.
Python.
20. Write a program to display the sum of n natural
numbers. 36. (a) Explain the following function.
a) id( ) b) type ( ) c) lower ( )

ok
21. Describe the abs ( ) and chr ( ) function. d) max ( ) d) min ( )
22. What is a Set? Give example. (OR)
23. List the types of database model. (b) Write a python program to check whether
o
the given string is palindrome or not
24. Define primary key Constraint.
37. (a) 
Explain the different SET operations in
ab

PART - III python.


Answer any 6 questions. Q.No. 33 is compulsory.
 6 × 3 = 18 (OR)
(b) How will you create the class, and objects in
25. Write an algorithmic function definition to find
python.
ur

the minimum among 3 numbers.


26. Differentiate Constructors and Selectors. 38. (a) Write the output for the following program.
str="COMPUTER"
27. Write a note on Asymptotic notation. index=0
.s

28. Write a syntax of while loop. for i in str:


print(str[: index+1])
29. Evaluate the following function. index + = 1
a) math.ceil (3.5) b) abs (–3.2) c) Pow (2,0)
w

(OR)
30. What is the use of format ( ) function? Give an (b) Explain the following commands in SQL
example. language.
w

31. What is reverse indexing in List? a) CREATE


32. Write the difference between SELECT and b) SELECT
PROJECT Command. c) DELETE
w

33. What is Constructor? d) ALTER


e) DROP



orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

12
th
Half Yearly Examination - 2019
STD.
PART - III Reg. No.

Time : 3.00 Hours] Computer Science [Maximum Marks : 70

m
Instructions : 4. In dynarnic programming, the technique of
storing the previously calculated values is called.

co
(a) Check the question paper for fairness of
printing. If there is any lack of fairness, (a) Saving value property
inform the Hall Supervisor Immediately. (b) Storing value property

(b) Use Blue or Black ink to write and underline (c) Memorization

s.
and pencil to draw diagrams. (d) Mapping

PART - I 5. Which of the following is not a Relational


operator?

ok
Note : (i) Answer all the questions.
 [15 × 1 = 15] (a) = (b) = = (c) > = (d) < =

(ii) 
Choose the most appropriate 6. Which statement is used to skip the remaining
answer from the given four part of a loop and start with next iteration?
o
alternatives and write the option (a) break (b) continue
code and the corresponding (c) return (d) goto
ab

answer.
7. Evaluate the following function and write the
1. The values which are passed to a function
output
definition are called
x = –37.9
(a) Arguments
ur

print(math.ceil(x))
(b) Subroutines (a)
–38 (b)
–39 (c)
–36 (d)
–37
(c) Function
8. Defining strings within triple quotes allows
.s

(d) Function definition creating


2. The datatype whose representation is unknown (a) Single line string
w

is called (b) Multiline strings


(a) Built-in datatype (c) Double line strings
(b) Derived datatype (d) Multiple strings
w

(c) Concrete datatype 9. Which of the following statement is not correct?


(d) Abstract datatype (a) The extend( ) function is used in tuple to
w

add elements in a list.


3. Which of the following is used in programming
(b) The append( ) function is used to add an
languages to map the variable and object?
element.
(a) : : (b) : =
(c) A tupe is immutable.
(c) = (d) = = (d) A list is mutable.

[ 249 ]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

250
Sura’s ➠ 12th Std - Computer Science - Half Yearly Examination - 2019

10. The process of creating an object is called as 20. What are the main advantages of function?
(a) Constructor (b) Destructor 21. What will be the output of the following Python
(c) Initialize (d) Instantiation Code?
str=“Chennai”
11. Relational database model was first proposed by

m
print(str*4)
(a) EE Codd (b) EF Codd
(c) EF Cadd (d) EF Codder 22. How will you access the list elements in reverse
order?

co
12. The clause used to sort data in database
23. Differentiate Python and C++.
(a) SORT BY (b) GROUP BY
(c) ORDER BY (d) SELECT 24. Define Data Visualization.

s.
13. Importing C++ program in a Python program PART - III
is called Answer any six questions in which Question

ok
(a) Wrapping (b) Downloading number 33 is compulsory. 6 × 3 = 18
(c) Interconnecting (d) Parsing 25. Why access control is required?
14. The most commonly used statement in SQL is 26. List the difference between break and continue
o
(a) cursor (b) commit statements.
(c) execute (d) select
27. What is the use of format( )? Give an example.
ab

15. Identify the package manager for Python


28. What are the difference between List and
packages, or modules
Dictonary?
(a) Matplot_lib (b) PIP
29. Write a Python program to check and print if
ur

(c) plt.show( ) (d) Python package


the given number is odd or even using class.
PART - II 30. What is constraint? Write short notes on primary
Answer any six questions. in which question key constraint.
.s

number 24 is compulsory. 6 × 2 = 12
31. Write a note on open( ) function of Python. What
16. What are subroutine? is the difference between the two methods?
w

17. What is searching? Write its types. 32. What is SQLite? What is its advantage?

18. Write short notes on tokens. 33. Write any three uses of data visualization.
w

19. Write a Python program to print. PART - IV


1 Answer all the questions:.
w

5 × 5 = 25
1 2 34. (a) Write any five characteristics of Module.
1 2 3 (OR)
1 2 3 4 (b) Write any five characteristics of Algorithm.
1 2 3 4 5

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ 12th Std - Computer Science - Half Yearly Examination - 2019 251

35. (a) Explain the various operators in Python. (i) 


To display the details of all students in
(OR) ascending order of name.
(b) Write a detail note on if..... else..... elif
(ii) To display all students in A2 group.
statement with suitable example.
36. (a) Explain the scope of variable with example (iii) To display the details group wise.

m
in Python.
(iv) To add new row
(OR)
(b) Explain about string operators in Python with (v) To remove students who are in B1 group.

co
suitable example. (OR)
37. (a) What is the purpose of range( ) in Python (b) Mylist = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
list? Explain with an example.

Write the Python commands for the
(OR)

s.
following based on above list.
(b) Explain the different types of data model.
(i) To print all elements in list.
38. (a) Consider the following student table. Write

ok
(ii) Find list length
SQL command for the questions (i) to (v).
Roll No. Name Group (iii) Add multiple elements [110, 120, 130]
1001 Ganesh A1 (iv) 
Delete from fourth element to seventh
1002 Kumar A2 element.
o
1003 Mani B1
1004 Raju A1 (v) Delete entire list.
ab

1005 Thulasi A2
1006 Geetha B1
1007 Latha A1
1008 Banu A2
1009 Kavya B1
ur
.s


w
w
w

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

12th
STD
PUBLIC EXAM QUESTION PAPER MARCH - 2020
COMPUTER SCIENCE (with Answers)
Reg. No.

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

m
Instructions : 6. Whats is the output of the following snippet? 
1) Check the question paper for fairness of for i in range (2,10,2) :
printing. If there is any lack of fairness, print (i, end='')

co
inform the Hall Supervisor Immediately. (a) 8 6 4 2 (b) 2 4 6 8 10
2) Use Blue or Black ink to write and underline (c) 2 4 6 8 (d) 2 4 6
and pencil to draw diagrams
7.
Evaluate the following function and write the
PART - I output.

s.
Note : Choose the most appropriate answer from the x=14.4
given four alternatives and write the option print(math.floor(x))
code and the corresponding answer. (a) 13 (b) 14
 [15 × 1 = 15]

ok
(c) 15 (d) 14.3
1. The functions which will give exact result when
8. What will be the output of the following code?
same arguments are passed are called :
str="NEW DELHI"
(a) Pure functions
str[3]="-"
(b) Impure functions
(a) NEW-DELHI (b) NE-DELHI
o
(c) Partial functions
(c) NEW DELHI (d) NEW-ELHI
(d) Dynamic functions
ab

9. The keys in Python, dictionary is specified by :


2. A sequence of immutable objects is called :
(a) ; (b) = (c) : (d) +
(a) Derived data (b) Built in
(c) List (d) Tuple 10. Class members are accessed through which
operator?
3. Which of the following members of a class can
ur

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


be handled only from within the class?
(a) Public members 11. What symbol is used for SELECT statement?
(b) Private members (a) Ω (b) σ (c) p (d) X
.s

(c) Protected members 12. The command to delete a table is :


(d) Secured members (a) DROP (b) ALTER TABLE
4. Two main measures for the efficiency of an (c) DELETE (d) DELETE ALL
w

algorithm are :
13. A CSV file is also known as a :
(a) Data and space
(a) Random File (b) String File
(b) Processor and memory
(c) 3D File (d) Flat File
w

(c) Complexity and capacity


(d) Time and space 14. A framework for interfacing Python and C++ is :
(a) Ctypes (b) Boost
5. Expand IDLE :
(c) SWIG (d) Cython
w

(a) Integrated Design Learning Environment


(b) Insert Development Learning Environment 15. Which of the following is an organized collection
(c) Integrated Develop Learning Environment of data?
(d) Integrated Development Learning (a) Records (b) Information
Environment (c) DBMS (d) Database

[252]

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ 12th Std - Computer Science - Public Exam Question Paper March - 2020 253

PART - II PART - IV
Note : Answer any six questions. Question No. 24 Note : Answer all the questions:. 5 × 5 = 25
is compulsory. 6 × 2 = 12
16. What is a Pair? Give an example. 34. (a) D
 iscuss about Linear Search algorithm with
example.
17. What do you mean by Namespaces?
18. What is an Algorithm? (OR)

m
19. Write note on range () in loop. (b) E
 xplain input () and print () functions with
example.
20. Write categories of SQL commands.
21. Write the expansion of : (i) SWIG (ii) MinGW 35. (a)(i) Write a program to display all 3 digit even

co
22. What is the advantage of declaring a column as numbers.
(ii) Write the output for the following program.
"INTEGER PRIMARY KEY"?
i=1
23. List the general types of data visualization. while(i<=6):
24. What will be the output of the given Python for j in range (1,i):

s.
program? print(j,end='\t')
str="COMPUTER SCIENCE" print(end='\n')
(a) print(str*2)  (b) print(str[0:7]) i+=1

ok
PART - III (OR)
Note : Answer any six questions. Question No. 33 (b) E
 xplain the following built-in functions.
is compulsory. 6 × 3 = 18 (a) id() (b) chr()
25. Differentiate pure and impure function. (c) round() (d) type()
o
26. Write a note on Asymptotic notation. (e) pow()
27. Explain Ternary operator with example.
36. (a) W
 rite the output for the following Python
ab

28. How recursive function works?


29. What will be the output of the following code? commands :
list=[3**x for x in range(5)] str1="Welcome to Python"
print(list) (i) print(str1)
30. Write short notes on TCL commands in SQL. (ii) print(str1[11 : 17])
ur

31. What is the difference between reader() and (iii) print(str1[11 : 17 : 2])
(iv) print(str1[: : 4])
DictReader() function?
32. Mention the difference between fetchone() and (v) print(str1[: : –4])
.s

fetchmany(). (OR)
(b) H
 ow do define constructor and destructor
33. Write the output of the following program. in Python? Explain with example.
class Hosting:
w

def __init__(self, name): 37. (a) Explain the different set operations supported
self.__name = name by Python with suitable example.
def display(self): (OR)
w

print("Welcome to", self.__name) (b) Differentiate DBMS and RDBMS.


obj=Hosting("Python Programming")
38. (a) W
 rite a SQL statement to create a table for
obj.display() employee having any five fields and create a
w

table constraint for the employee table.


(OR)
(b) W
 rite the features of Python over C++.



orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

254
Sura’s ➠ 12th Std - Computer Science - Public Exam Question Paper March - 2020

ANSWER 21. (i) S


 WIG – Simplified Wrapper Interface
Generator – Both C and C++.
PART - I
(ii) MINGW – Minimalist GNU for Windows
1. (a) Pure functions
22. If a column of a table is declared to be an
2. (d) Tuple INTEGER PRIMARY KEY, then whenever a
3.

m
(b) Private members NULL is used as an input for this column, the
4. (d) Time and space NULL will be automatically converted into an
5. (d) Integrated Development Learning integer which will be one larger than the highest
value so far used in that column.
Environment

co
If the table is empty, the value 1 will be used.
6. (c) 2 4 6 8
7. (b) 14 23. (i) Charts
8. (a) NEW - DELHI (ii) Tables
9. (c) : (iii) Graphs

s.
10. (a) . (iv) Maps
11. (b) σ (v) Infographics
12. (a) DROP (vi) Dashboards

ok
13. (d) Flat File 24. (a)  Output : COMPUTER SCIENCE
14. (b) Boost COMPUTER SCIENCE
15. (d) Database (b) Output : COMPUTE
PART - II PART - III
o
16. (i) Any way of bundling two values together 25.
into one can be considered as a Pair. Lists S. No. Pure Impure
ab

are a common method to do so. Therefore (i) The return value of The return value
List can be called as Pairs. the pure functions of the impure
(ii) Example : List = [(10,10), (1,20)] solely depends on its functions does not
arguments passed. solely depend on its
17. Namespaces are containers for mapping names arguments passed.
ur

of variables to objects. (ii) If you call the pure If you call the
Example : a : = 5 functions with impure functions
Here the variable 'a' is mapped to the value '5'. the same set of with the same set of
18. An algorithm is a finite set of instructions to arguments, you will arguments,
.s

accomplish a particular task. It is a step-by-step always get the same you might get the
return values. different return
procedure for solving a given problem.
values.
19. range() generates a list of values starting from
(iii) They do not have any They have side
w

start till stop-1.


side effects. effects. For example,
range (start,stop,[step]) random(), Date().
Where, (iv) They do not modify They may modify
w

start – refers to the initial value the arguments which the arguments which
stop – refers to the final value are passed to them are passed to them
step – refers to increment value, this is optional 26. Asymptotic Notations are languages that uses
part.
w

meaningful statements about time and space


20. (i) DDL - Data Definition Language complexity. The following three asymptotic
notations are mostly used to represent time
(ii) DML - Data Manipulation Language
complexity of algorithms:
(iii) DCL - Data Control Language
(i) Big O : Big O is often used to describe the
(iv) TCL - Transaction Control Language worst-case of an algorithm.
(v) DQL - Data Query Language

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ 12th Std - Computer Science - Public Exam Question Paper March - 2020 255

(ii) Big Ω : Big Omega is the reverse Big O, if (iii) csv. Reader work with list/tuple.
Bi O is used to describe the upper bound (iv) Syntax: csv.reader(fileobject,delimiter,
(worst - case) of a asymptotic function, Big fmtparams)
Omega is used to describe the lower bound
(best-case). DictReaer() :
(iii) Big Θ : When an algorithm has a complexity (i) DictReader works by reading the first

m
with lower bound = upper bound, say that line of the CSV and using each comma
an algorithm has a complexity O (n log separated value in this line as a dictionary
n) and Ω (n log n), it’s actually has the key.
complexity Θ (n log n), which means the

co
(ii) DictReader is a class of csv module is used
running time of that algorithm always falls to read a CSV file into a dictionary.
in n log n in the best-case and worst-case.
(iii) It creates an object which maps data to a
27. (i) Ternary operator is also known as dictionary.
conditional operator that evaluate
(iv) csv.DictReader work with dictionary.

s.
something based on a condition being true
or false. 32.
(ii) It simply allows testing a condition in a fetchone() fetchmany()
single line replacing the multiline if-else

ok
making the code compact. (i) The fetchone() method The fetchmany()
returns the next row of a method returns the
Syntax : query result set or None in next number of rows
Variable Name = [on_true] if [Test case there is no row left (n) of the result set.
expression] else [on_false] (ii) Using while loop and Displaying specified
o
(iii) Example: fetchone() method we number of records
can display all the records is done by using
min = 50 if 49 < 50 else 70 // min = 50 from a table. fetchmany().
ab

min = 50 if 49 > 50 else 70 // min = 70 33. Output : Welcome to Python Programming.


28. (i)  Recursive function is called by some
external code. PART - IV
(ii) If the base condition is met then the 34. (a) ( i) Linear search also called sequential
program gives meaningful output and
ur

search is a sequential method for finding


exits. a particular value in a list.
(iii) Otherwise, function does some required
processing and then calls itself to continue (ii) This method checks the search element with
recursion. each element in sequence until the desired
.s

element is found or the list is exhausted. In


29. Output : [1,3,9,2,7,81] this searching algorithm, list need not be
30. (i) Commit : Saves any transaction into the ordered.
database permanently. Pseudo code :
w

(ii) Roll back :Restores the database to last (i) Traverse the array using for loop
commit state. (ii)  In every iteration, compare the target
(iii) Save point : Temporarily save a transaction search key value with the current value of
w

so that you can rollback. the list.


31. Reader(): ■  If the values match, display the
current index and value of the array
(i) The reader function is designed to take
■ If the values do not match, move on to
w

each line of the file and make a list of all


the next array element.
columns.
(iii) If no match is found, display the search
(ii) Using this method one can read data from element not found.
csv files of different formats like quotes
(" "), pipe (|) and comma (,). Example
To search the number 25 in the array given
below, linear search will go step by step in
a sequential order starting from the first

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

256
Sura’s ➠ 12th Std - Computer Science - Public Exam Question Paper March - 2020

element in the given array if the search (vii) Note that in example-2, the input( ) is not
element is found that index is returned having any prompt string, thus the user
otherwise the search is continued till the will not know what is to be typed as input.
last index of the array. In this example If the user inputs irrelevant data as given
in the above example, then the output will
number 25 is found at index number 3. be unexpected. So, to make your program
index 0 1 2 3 4 more interactive, provide prompt string

m
values 10 12 20 25 30 with input( ).
(viii) The input ( ) accepts all data as string
Example 1 :
or characters but not as numbers. If a

co
Input: values[] = {5, 34, 65, 12, 77, 35} numerical value is entered, the input
target = 77 values should be explicitly converted into
Output: 4 numeric data type. The int( ) function is
Example 2: used to convert string data as integer data
Input: values[] = {101, 392, 1, 54, 32, 22, 90, 93} explicitly.

s.
target = 200
(ix) Example 3 :
Output: -1 (not found)
x = int (input(“Enter Number 1: ”))
(OR)

ok
(b) I nput and Output Functions : A program y = int (input(“Enter Number 2: ”))
needs to interact with the user to accomplish print (“The sum = ”, x+y)
the desired task; this can be achieved using Output :
Input-Output functions. The input() function
helps to enter data at run time by the user and Enter Number 1: 34
o
the output function print() is used to display Enter Number 2: 56
the result of the program on the screen after The sum = 90
execution.
ab

The input() function : The print() function :


(i)  In Python, input( ) function is used to (i) In Python, the print() function is used to
accept data as input at run time. The syntax display result on the screen. The syntax for
for input() function is, print() is as follows :
Variable = input (“prompt string”) (ii) Example :
ur

(ii) Where, prompt string in the syntax is a


print (“string to be displayed as output ” )
statement or message to the user, to know
what input can be given. print (variable )
(iii) If a prompt string is used, it is displayed on print (“String to be displayed as output ”,
.s

the monitor; the user can provide expected variable)


data from the input device. The input( )  print (“String1 ”, variable, “String 2”,
takes whatever is typed from the keyboard
 variable, “String 3” ……)
and stores the entered data in the given
w

variable. (iii) Example :


(iv) If prompt string is not given in input( ) no >>> print (“Welcome to Python
message is displayed on the screen, thus, Programming”)
the user will not know what is to be typed Welcome to Python Programming
w

as input. >>> x = 5
(v) Example 1 : input( ) with prompt string
>>> y = 6
>>> city=input (“Enter Your City: ”)
>>> z = x + y
w

Enter Your City: Madurai


>>> print (“I am from “, city) >>> print (z)
I am from Madurai 11
(vi) Example 2 : input( ) without prompt string >>> print (“The sum = ”, z)
>>> city=input() The sum = 11
Madurai >>> print (“The sum of ”, x, “ and ”, y, “ is
>>> print (I am from", city) ”,  z)
I am from Madurai
The sum of 5 and 6 is 11

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ 12th Std - Computer Science - Public Exam Question Paper March - 2020 257

(iv) The print ( ) evaluates the expression 4. type ( ) Returns the type x= 15.2
before printing it on the monitor. type of object (object) y= 'a'
(v) The print () displays an entire statement for the given s= True
which is specified within print ( ). Comma single object. print (type (x))
(,) is used as a separator in print ( ) to print Note: print (type (y))
This function print (type (s))
more than one item.

m
used with Output:
single object <class 'float'>
35. (a)(i) for i range (100, 999, 2); <class 'str'>
print (i, end = '\t') parameter.
<class 'bool'>
else;

co
5. pow ( ) Returns the pow (a,b) a= 5
print ("\n End of the loop") computation b= 2
Output : 100, 102, 104, ......... 998 of ab i.e. c= 3.0
(ii) 1 (a**b) a print (pow
1 2 raised to the (a,b))
power of b. print (pow

s.
1 2 3
(a,c))
1 2 3 4 print (pow
1 2 3 4 5 (a+b,3))
(OR) Output:

ok
(b) 25
125.0
S. 343
Function Description Syntax Example
No
36. (a) (i) Welcome to Python
1. id () id( ) Return id (object) x=15
o
(ii) Python
the “identity” y='a' (iii) Pto
of an object. print ('address (iv) wotyn
ab

i.e. the of x is :',id (x))


address of (v) nytow
the object in print ('address (OR)
memory. of y is :',id (y)) (b) C onstructor :
Note: Output: (i) Constructor is the special function that
The address of is automatically executed when an object
ur

address of x is :
x and y may of a class is created. In Python, there is a
differ in your 1357486752
address of y is : special function called “init” which act as a
system.
13480736 Constructor.
(ii) It must begin and end with double
.s

2. chr ( ) Returns the chr (i) c=65


Unicode underscore.
d=43
character (iii) Constructor function will automatically
print (chr (c))
for the given executed when an object of a class is
w

prin t(chr (d))


ASCII value. created.
Output:
This function General format of constructor :
is inverse A def__init__(self, [args ................]):
of ord() + <statements>
w

function. Example : Program to illustrate Constructor


3. round ( ) Returns round x= 17.9 class Sample:
the nearest (number y= 22.2 def __init__(self, num):
w

integer to its [,ndigits]) z= -18.3 print("Constructor of class Sample...")


input. print ('x value
self.num=num
1. F
 irst is rounded to',
round (x)) print("The value is :", num)
argument
(number) print ('y value S=Sample(10)
is used to is rounded to', Destructor :
specify the round (y)) (i) Destructor is also a special method gets
value to be print ('z value executed automatically when an object exit
rounded. is rounded to', from the scope.
round (z))

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

258
Sura’s ➠ 12th Std - Computer Science - Public Exam Question Paper March - 2020

(ii) In Python, __del__() method is used as


destructor. Set A Set B
General format of constructor :
def__del__(self):
<statements>
Example : Program to illustrate about the

m
__del__( ) method

class Sample:
num=0 (ii) The operator & is used to intersect two sets
def __init__(self, var): in python. The function intersection( ) is

co
also used to intersect two sets in python.
Sample.num+=1
self.var=var (iii) Example : Program to insect two sets using
print("The object value is = ", var) intersection operator
print("The value of class variable is= set_A={'A', 2, 4, 'D'}
", Sample.num) set_B={'A', 'B', 'C', 'D'}

s.
def __del__(self): print(set_A & set_B)
Sample.num-=1 Output :
print("Object with value %d is exit {'A', 'D'}

ok
from the scope"%self.var) Difference :
S1=Sample(15) (i) It includes all elements that are in first set
S2=Sample(35) (say set A) but not in the second set (say set B)
S3=Sample(45)
Set A Set B
37. (a) A set is a mutable and an unordered collection
o
of elements without duplicates.
Set operations: The set operation such
ab

as Union, Intersection, difference and


symmetric difference.
Union: It includes all elements from two or
more sets (ii) The minus (–) operator is used to difference
ur

Set A Set B set operation in python. The function


difference( ) is also used to difference
operation.
(iii) Example : Program to difference of two
.s

sets using minus operator



set_A={'A', 2, 4, 'D'}
(i) In python, the operator | is used to union of
set_B={'A', 'B', 'C', 'D'}
w

two sets. The function union( ) is also used


to join two sets in python. print(set_A - set_B)
(ii) Example : Program to Join (Union) two Output : {2, 4}
sets using union operator
w

set_A={2,4,6,8} Symmetric difference :


set_B={'A', 'B', 'C', 'D'} (i) It includes all the elements that are in two
U_set=set_A|set_B sets (say sets A and B) but not the one that
w

print(U_set) are common to two sets.


Output :
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
Intersection :
(i) It includes the common elements in two
sets

orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

Sura’s ➠ 12th Std - Computer Science - Public Exam Question Paper March - 2020 259

Basis of
DBMS RDBMS
Set A Set B Comparison
Keys and indexes Does not use. used to establish
relationship.
Keys are used in
RDBMS.

m
Transaction Inefficient, Efficient and
management Error prone and secure.
insecure.
(ii) The caret (^) operator is used to symmetric

co
Distributed Not supported Supported by
difference set operation in python. The Databases RDBMS.
function symmetric_difference( ) is also Example Dbase, FoxPro. SQL server,
used to do the same operation. Oracle, mysql,
MariaDB, SQLite.
(iii) Example : Program to symmetric difference

s.
38. (a) C
 REATE TABLE employee
of two sets using caret operator
(
set_A={'A', 2, 4, 'D'} empcode integer NOTNULL,

ok
set_B={'A', 'B', 'C', 'D'} name char(20),
print(set_A ^ set_B) desigchar(20),
Pay integer,
Output :
allowance integer,
{2, 4, 'B', 'C'} PRIMARY KEY (empno)
o
(OR) );
(b) (OR)
ab

Basis of (b) ( i) Python uses Automatic Garbage


DBMS RDBMS Collection whereas C++ does not.
Comparison
Expansion Database Relational (ii) C++ is a statically typed language, while
Management DataBase Python is a dynamically typed language.
System Management (iii) Python runs through an interpreter,
ur

System while C++ is pre-compiled.


Data storage Navigational Relational model (iv) Python code tends to be 5 to 10 times
model (in tables). ie data
shorter than that written in C++.
ie data by in tables as row
(v) In Python, there is no need to declare
.s

linked records and column


types explicitly where as it should be
Data redundancy Exhibit Not Present
done in C++
Normalization Not performed RDBMS uses (vi) In Python, a function may accept an
w

normalization
to reduce argument of any type, and return
redundancy multiple values without any kind of
declaration beforehand. Whereas in
Data access Consumes Faster, compared
w

more time to DBMS. C++ return statement can return only


one value.
w



orders@surabooks.com Ph: 9600175757 / 8124201000


This is only for Sample
for Full Book order Online and Available at All Leading Bookstores
www.asiriyar.net

260
Sura’s ➠ 12th Std - Computer Science - Public Exam Question Paper March - 2020

[Notes]

m
co
s.
o ok
ab
ur
.s
w
w
w

orders@surabooks.com Ph: 9600175757 / 8124201000

SURA PUBLICATIONS
Chennai
	 Exhaustive Additional MCQs, VSA and SA question with answers are given in each chapter.
	 All
iii
Contents
Unit
Chapter 
No
Title
Page 
No
UNIT- I
Problem 
Solving 
Techniques
1.
Function
1-8
2.
Data Abstraction
9-17
3.


[1]
1.1	
Introduction
1.2	
Function with respect to Programming language
	
1.2.1 	 Function Specification 
	
1.2.2 	 Par

2
 Sura’s ➠ XII Std - Computer Science
Unit I - Chapter 1
8.	
Which of the following carries out the 
instructions define

3
 Sura’s ➠ XII Std - Computer Science
Function
(iv) 	 Here, the result of inc() will change every 
time if the value of '

4
 Sura’s ➠ XII Std - Computer Science
Unit I - Chapter 1
	
■  	
When we write the type annotations for 
‘a’ and ‘b’ the

5
 Sura’s ➠ XII Std - Computer Science
Function
4.	
Explain with an example interface and 
implementation.
Ans.	Interface

6
 Sura’s ➠ XII Std - Computer Science
Unit I - Chapter 1
Government Exam Questions and Answers
2 MARKS
1.	
Define pure f

7
 Sura’s ➠ XII Std - Computer Science
Function
3.	
Explicitly _____________ the types can help 
with debugging.
(a)	 defi

8
 Sura’s ➠ XII Std - Computer Science
Unit I - Chapter 1
Short Answers
3 MARKS
1.	
Explain the syntax of function defin

You might also like