12th Computer Science Sura Guide 2023 24 EM (1)
12th Computer Science Sura Guide 2023 24 EM (1)
com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
COMPUTER SCIENCE
m
e
12 Standard
th FreWorkbook
e
Practic with
co
anual
Lab M
Based on the Updated New Textbook
.
Salient Features
ks
Answers for all Textual Questions.
Exhaustive Additional MCQs, VSA and SA question with answers are given in each chapter.
oo
All the objective type (1 Mark) questions are given with 4 options.
(i) Choosing the correct option
(ii) Matching
ab
Model Question Papers 1 to 6 (PTA) : Questions are incorporated in the appropriate sections.
Govt. Model Question Paper - 2019 (Govt. MQP-2019), Quarterly Exam - 2019 (QY-2019),
Half Yearly Exam - 2019 (HY-2019), Public Exam March - 2020 & May 2022 (Mar-2020 &
.s
May-2022), Supplementary Exam September - 2020, August 2021 & July-2022 (Sep-2020,
Aug-2021 & July-'22) and First & Second Revision Test - 2022 (FRT-'22 & SRT-'22) questions
are incorporated in the appropriate sections.
w
Instant Supplementary Exam July 2022 Question Paper is given with answers.
w
w
SURA PUBLICATIONS
Chennai
2023-24 Edition
All rights reserved © SURA Publications.
No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or
by any means, digitally, electronically, mechanically, photocopying, recorded or otherwise, without the
written permission of the publishers. Strict action will be taken.
m
ISBN : 978-93-5330-523-9
Code No : SG91
co
Author :
Mr. Shanmugasundaram
.
(Post Graduate Teacher, Chennai)
ks
Edited by :
Mrs. Malathy Krishnamoorthy M.Sc.,
Erode
oo
Reviewed by :
Mr. Balaji M.Sc., M.Phil.
Chennai
ab
e-mail : [email protected]
website : www.surabooks.com
78718 02000
98409 26027
ii
TO ORDER WITH US
SCHOOLS and TEACHERS:
We are grateful for your support and patronage to ‘SURA PUBLICATIONS’
Kindly prepare your order in your School letterhead and send it to us.
For Orders contact: 81242 01000 / 81243 01000
DIRECT DEPOSIT
m
A/c Name : Sura Publications A/c Name : Sura Publications
Our A/c No. : 36550290536 Our A/c No. : 21000210001240
Bank Name : STATE BANK OF INDIA Bank Name : UCO BANK
co
Bank Branch : Padi Bank Branch : Anna Nagar West
IFSC : SBIN0005083 IFSC : UCBA0002100
.
Bank Name : INDIAN BANK Bank Name : KVB BANK
ks
Bank Branch : Asiad Colony Bank Branch : Anna Nagar
IFSC : IDIB000A098 IFSC : KVBL0001154
IFSC : ICIC0004462
After Deposit, please send challan and order to our address.
email to : [email protected] / Whatsapp : 81242 01000.
.s
in School letterhead.
STUDENTS :
Order via Money Order (M/O) to
w
Sura Publications
1620, ‘J’ Block, 16th Main Road, Anna Nagar, Chennai - 600 040.
Phones : 044-4862 9977, 044-4862 7755.
Mobile : 96001 75757 / 81242 01000 / 81243 01000.
email : [email protected] Website : www.surabooks.com
iv
Contents
Chapter Page
Unit
No
Title No
Month
m
1. Function 1-8 June
UNIT- I
2. Data Abstraction 9-17 June
co
Problem
Solving 3. Scoping 18-27 June
Techniques
4. Algorithmic Strategies 28-43 June
.
ks
5. Python -Variables and Operators 44-60 July
Core Python 7.
oo
Python functions 78-98 July
Modularity and
OOPS 10. Python Classes and objects 139-151 Aug
Database
12. Structured Query Language (SQL) 170-191 Oct
concepts and
MySql 13. Python and CSV files 192-209 Oct
.s
238-250
C++ chart, pie chart and bar chart
Instant Supplementary Exam July 2022 Question Paper with answers 251-258
w
UNIT-I
PROBLEM SOLVING TECHNIQUES
1
Chapter
FUNCTION
m
co
CHAPTER SNAPSHOT
1.1 Introduction
1.2 Function with respect to Programming language
.
1.2.1 Function Specification
ks
1.2.2 Parameters (and arguments)
1.3 Interface Vs Implementation
1.3.1 Characteristics of interface
1.4 Pure functions
oo
1.4.1 Impure functions
1.4.2 Side-effects (Impure functions)
1.4.3 Chameleons of Chromeland problem using function
ab
[1]
Unit I - Chapter 1
8.
Sura’s
Available at All Leading Bookstores
m
[PTA-3; Mar.-2020] if (num!=0) then return num + sum
(a) Impure functions (b) Partial Functions (num-1)
(c) Dynamic Functions (d) Pure functions else
co
[Ans. (d) Pure functions] return num
10. The functions which cause side effects to the Ans. (i) Recursive function
arguments passed are called (ii) Normal function
(a) Impure function (b) Partial Functions (iii) Recursive function
.
(c) Dynamic Functions (d) Pure functions
Part - III
ks
[Ans. (a) Impure function]
Part - II Answer the following questions
Answer the following questions (3 marks)
(2 marks) 1. Mention the characteristics of Interface.
oo
1. What is a subroutine? [PTA-1; HY-2019] [Sep-2020]
Ans. (i) Subroutines are the basic building blocks of Ans. (i) The class template specifies the interfaces to
computer programs. Subroutines are small enable an object to be created and operated
sections of code that are used to perform a properly.
ab
particular task that can be used repeatedly. (ii) An object's attributes and behaviour is
(ii) In Programming languages these controlled by sending functions to the object.
subroutines are called as Functions. 2. Why strlen is called pure function?
2. Define Function with respect to Programming [Govt. MQP-2019]
ur
language. [Aug-2021; FRT-'22] Ans. (i) strlen is a pure function because the function
Ans. A function is a unit of code that is often defined takes one variable as a parameter, and accesses
within a greater code structure. Specifically, a it to find its length.
function contains a set of code that works on (ii) This function reads external memory but does
.s
many kinds of inputs, like variants, expressions not change it, and the value returned derives
and produces a concrete output. from the external memory accessed.
3. What is the side effect of impure function. Give
w
definition. Definitions bind values to names, in (i) Function impure (has side effect) is that it
this case the value 78 being bound to the name doesn't take any arguments and it doesn't
‘X’. return any value.
w
Available at All Leading Bookstores
Function
(v) Hence, the side effect of inc () function (5 marks)
is changing the data of the external 1. What are called Parameters and write a note
variable 'y'. on [PTA-2; May-'22]
m
4. Differentiate pure and impure function. (i) Parameter without Type [FRT-'22]
(ii) Parameter with Type
Ans. [PTA-3, 6; Mar.-2020]
Ans. Parameters (and arguments) : Parameters
S. No. Pure Impure
co
are the variables in a function definition and
(i) The return value of The return value arguments are the values which are passed to a
the pure functions of the impure function definition.
solely depends functions does (i) Parameter without Type : Let us see an
on its arguments not solely depend example of a function, definition :
.
passed. on its arguments (requires: b>=0 )
ks
passed. (returns: a to the power of b)
(ii) If you call the pure If you call the let rec pow a b:=
functions with impure functions if b=0 then 1
else a * pow a (b –1)
the same set of
oo
with the same set
arguments, you will of arguments, ■ In the above function definition variable
‘b’ is the parameter and the value which is
always get the same you might get the
passed to the variable ‘b’ is the argument.
return values. different return The precondition (requires) and
ab
strlen(), sqrt() random(), Date(). solves this type (data type) inference
(iv) They do not modify They may modify problem algorithmically, but some require
the arguments the arguments the type to be mentioned.
■ In the above function definition if
.s
Unit I - Chapter 1
Sura’s
Available at All Leading Bookstores
m
times when you get a type error from function once. Lt’s see an example
the compiler that doesn't make sense.
let i: = 0;
Explicitly annotating the types can help
if i <strlen (s) then
co
with debugging such an error message.
-- Do something which doesn't affect s
2. Identify in the following program [PTA-5] ++i
let rec gcd a b := (vi) If it is compiled, strlen (s) is called each
if b <> 0 then gcd b (a mod b) else return a time and strlen needs to iterate over the
.
whole of ‘s’. If the compiler is smart enough
ks
i) Name of the function to work out that strlen is a pure function
ii) Identify the statement which tells it is a and that ‘s’ is not updated in the loop, then
recursive function it can remove the redundant extra calls to
iii) Name of the argument variable strlen and make the loop to execute only
iv)
oo
Statement which invoke the function one time.
recursively (vii) From these what we can understand, strlen
v) Statement which terminates the recursion is a pure function because the function
takes one variable as a parameter, and
Ans. (i) gcd
accesses it to find its length. This function
ab
(ii) let rec gcd reads external memory but does not
(iii) a, b change it, and the value returned derives
(iv) gcd b (a mod b) from the external memory accessed.
(v) return a Impure functions :
ur
(ii) For example the mathematical function sin you can never be sure that the function
(0) always results 0. This means that every will behave the same every time it’s called.
time you call the function with the same For example the mathematical function
w
arguments, you will always get the same random() will give different outputs for the
result. same function call.
let randomnumber:=
(iii) A function can be a pure function provided
w
4
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
Function
accelerator to get the desired behaviour.
An interface is a set of action that an object
(i) Here the accelerator is the interface
can do. For example when you press a light between the driver (the calling / invoking
switch, the light goes on, you may not have object) and the engine (the called object).
cared how it splashed the light. In Object (v) In this case, the function call would be
m
Oriented Programming language, an Speed (70): This is the interface. Internally,
Interface is a description of all functions the engine of the car is doing all the things
that a class must have in order to be a new It's where fuel, air, pressure, and electricity
interface.
co
come together to create the power to move
(ii) In our example, anything that "ACTS the vehicle.
LIKE" a light, should have function (vi) All of these actions are separated from the
definitions like turn_on () and a turn_off driver, who just wants to go faster. Thus we
(). The purpose of interfaces is to allow the separate interface from implementation.
.
computer to enforce the properties of the
Hands on Practice
ks
class of TYPE T (whatever the interface is)
must have functions called X, Y, Z, etc.
(iii) A class declaration combines the
1. Write algorithmic function definition to find
external interface (its local state) with an the minimum among 3 numbers.
Ans. let min 3 x y z :=
oo
implementation of that interface (the code
that carries out the behaviour). An object if x < y then
is an instance created from the class. The if x < z then x else z
interface defines an object’s visibility to the else
outside world. if y < z then y else z
ab
Implementation :
(i) Implementation carries out the instructions 2. Write algorithmic recursive function definition
defined in the interface. to find the sum of n natural numbers.
(ii) How the object is processed and executed is Ans. let rec sum num:
the implementation. if (num!=0) then return num+sum num-1)
ur
5
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
DATA ABSTRACTION
2
Chapter
m
co
CHAPTER SNAPSHOT
2.1 Data Abstraction – Introduction
.
2.2 Abstract Data Types
ks
2.3 Constructors and Selectors
2.4 Representation of Abstract datatype using Rational numbers
2.5 Lists, Tuples
2.5.1 List
oo
2.5.2 Tuple
2.6 Data Abstraction in Structure
ab
Unit I - Chapter 2
8.
Sura’s
considered as
Available at All Leading Bookstores
m
various parts of a multi-item object? [PTA-6] list.
(a) Tuples (b) Lists Example : lst := [10, 20]
(c) Classes (d) Quadrats x, y := lst
co
[Ans. (c) Classes] 5. What is a Tuple? Give an example.
10. Which of the following is constructed by Ans. (i) A tuple is a comma-separated sequence of
placing expressions within square brackets? values surrounded with parentheses. Tuple
(a) Tuples (b) Lists is similar to a list.
.
(c) Classes (d) Quadrats (ii) The difference between the two is that you
ks
[Ans. (b) Lists] cannot change the elements of a tuple once
it is assigned whereas in a list, elements can
Part - II be changed.
Answer the following questions (iii) Example : colour= ('red', 'blue', 'Green')
1. What is abstract data type? (2 marks)
oo Part - III
[Aug-2021; FRT & May-'22]
Answer the following questions
Ans. (i) Abstract Data type (ADT) is a type (or
class) for objects whose behavior is defined (3 marks)
ab
information.
2. Which strategy is used for program designing?
3. What is a Pair? Give an example. [Mar.-2020] Define that Strategy. [Govt. MQP-2019]
Ans. (i) Any way of bundling two values together Ans. A powerful strategy for designing programs:
into one can be considered as a Pair. Lists 'wishful thinking'. Wishful Thinking is the
are a common method to do so. Therefore formation of beliefs and making decisions
List can be called as Pairs. according to what might be pleasing to imagine
(ii) Example : lst = [(0,10), (1,20)] instead of by appealing to reality.
10
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
Data Abstraction
(a) N1=number() (c) Class
(b) accetnum(n1) (d) Tuple
(c) displaynum(n1)
(e) List
(d) eval(a/b)
(f) Class
(e) x,y= makeslope (m), makeslope(n)
Part - IV
m
(f) display()
Answer the following questions
Ans. (a) Constructors (5 marks)
co
(b) Selectors
1. How will you facilitate data abstraction.
(c) Selectors
Explain it with suitable example.
(d) Selectors
[PTA-2, 4; FRT-'22]
(e) Constructors
(f) Ans. Data abstraction is supported by defining an
.
Selectors
abstract data type (ADT), which is a collection
ks
4. What are the different ways to access the of constructors and selectors. To facilitate data
elements of a list. Give example. abstraction, you will need to create two types of
Ans. (i) The elements of a list can be accessed in functions: Constructors and Selectors
two ways. The first way is via our familiar Constructors :
oo
method of multiple assignment, which (i) Constructors are functions that build the
unpacks a list into its elements and binds abstract data type.
each element to a different name.
(ii) Constructors create an object, bundling
lst := [10, 20] together different pieces of information.
ab
elements in a list is by the element selection (v) To create a city object, you'd use a function
operator, also expressed using square like city = makecity (name, lat, lon).
brackets. Unlike a list literal, a square- (vi) Here makecity (name, lat, lon) is the
brackets expression directly following
.s
lst[0]
10 make city ( )
lst[1]
w
20
5. Identify Which of the following are List, Tuple city
and class ?
w
lat lon
(a) arr [1, 2, 34]
(b) arr (1, 2, 34) Constructor
11
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit I - Chapter 2
Sura’s
Available at All Leading Bookstores
m
city value passed as parameter city value passed as parameter city value passed as parameter Ans. (i) The structure construct (In OOP languages
it's called class construct) is used to
getname ( ) getlat ( ) getlon ( ) represent multi-part objects where each
co
part is named (given a name). Consider the
following pseudo code:
2. What is a List? Why List can be called as Pairs. class Person:
Explain with suitable example. [PTA-6] creation( )
.
Ans. List : firstName := " "
ks
(i) List is constructed by placing expressions
lastName := " "
within square brackets separated by
commas. Such an expression is called a list id := " "
literal. List can store multiple values. Each email := " "
value can be of any type and can even be The new data type Person is pictorially
another list.
oo represented as
Example for List is [10, 20].
Person class name (multi part data representation)
(ii) The elements of a list can be accessed in
two ways. The first way is via our familiar
ab
}
unpacks a list into its elements and binds
each element to a different name.
first Name
lst := [10, 20]
x, y := lst
ur
last Name
datatype
(iii) In the above example x will become10 and id
y will become 20. A second method for
accessing the elements in a list is by the email
.s
12
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
SCOPING
3
Chapter
m
CHAPTER SNAPSHOT
3.1 Introduction 3.5 Module
co
3.2 Variable Scope 3.5.1. Characteristics of Modules
3.3 LEGB rule 3.5.2. The benefits of using modular
3.4 Types of Variable Scope programming include
3.4.1. Local Scope 3.5.3. Access Control
.
3.4.2. Global Scope
ks
3.4.3. Enclosed Scope
3.4.4. Built-in-Scope
Available at All Leading Bookstores
Scoping
(b) Protected members the name of the variable/method with single or
(c) Secured members (d) Private members double underscore to emulate the behaviour of
[Ans. (a) Public members] protected and private access specifiers.
Example: self_n2 = n2
m
10. The members that are accessible from within
the class and are also available to its sub-classes Part - III
is called [PTA-6] Answer the following questions
(3 marks)
co
(a) Public members
1. Define Local scope with an example.
(b) Protected members
[Aug-2021]
(c) Secured members (d) Private members
Ans. (i) Local scope refers to variables defined in
[Ans. (b) Protected members]
current function. Always, a function will
.
Part - II first look up for a variable name in its local
ks
Answer the following questions scope.
(ii) Only if it does not find it there, the outer
(2 marks) scopes are checked.
1. What is a scope? oo (iii) Look at this example :
Ans. Scope refers to the visibility of variables,
1. Disp(): Entire program Output
parameters and functions in one part of a
2. a:=7 of the
program to another part of the same program.
3. print a Disp( ): Program
a:=7
2. Why scope should be used for variable. State 4. Disp() print a 7
ab
of the code. Essentially, variables are addresses and available in the local scope.
(references, or pointers), to an object in memory. 2. Define Global scope with an example.
When you assign a variable with := to an [PTA-6; FRT-'22]
.s
instance (object), you're binding (or mapping) Ans. (i) A variable which is declared outside of all
the variable to that instance. Multiple variable the functions in a program is known as
can be mapped to the same instance. Global variable.
(ii) This means, global variable can be accessed
w
a:=7
4. What do you mean by Namespaces? 4. print a print a 7
[Govt. MQP-2019; PTA-4; Mar.-2020; FRT & 5. Disp() Disp ( ): 10
print a
July-'22] 6. print a
Ans. Namespaces are containers for mapping names (iii) On execution of the above code the variable
of variables to objects. a which is defined inside the function
Example : a : = 5 displays the value 7 for the function call
Disp() and then it displays 10, because a is
Here the variable 'a' is mapped to the value '5'.
defined in global scope.
19
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit I - Chapter 3
3.
Sura’s
Available at All Leading Bookstores
m
function which contains another function Color:=Red Global
definition with in it, the inner function
b:=Blue Enclosed
can also access the variable of the outer
co
function. This scope is called enclosed G:=Green Local
scope.
Part - IV
(iii) When a compiler or interpreter search for a
variable in a program, it first search Local, Answer the following questions
.
and then search Enclosing scopes. Consider (5 marks)
ks
the following example
1. Disp(): Entire program Output 1. Explain the types of scopes for variable or
2. a:=10 Disp( ):
of the LEGB rule with example.
3. Disp1(): a:=10 Program [PTA-1; Sep-2020; May-'22]
4. print a
Disp 1( ):
oo 10
print a Ans. Types of Variable Scope :
5. Disp1() Disp 1( ) 10 There are 4 types of Variable Scope, let's discuss
print a
6. print a Disp( )
them one by one:
7. Disp() Local Scope : [FRT-'22]
ab
4. Why access control is required? (i) Local scope refers to variables defined in
[PTA-1; HY-2019] current function. Always, a function will
first look up for a variable name in its local
Ans. (i) Access control is a security technique that scope. Only if it does not find it there, the
regulates who or what can view or use
ur
20
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
Scoping
a:=7
Disp( ):
4. print a print a 7
Disp 1( ):
5. Disp() Disp ( ): 10 print a
print a
6. print a Disp 1( )
print a
m
(iii) On execution of the above code the variable Disp( )
'a' which is defined inside the function
displays the value 7 for the function call LEGB rule : [May-'22]
co
Disp() and then it displays 10, because a is
The LEGB rule is used to decide the order
defined in global scope.
in which the scopes are to be searched
Enclosed Scope : for scope resolution. The scopes are listed
(i) All programming languages permit below in terms of hierarchy (highest to
.
functions to be nested. A function (method) lowest).
ks
with in another function is called nested
Local(L) Defined inside function/
function.
class
(ii) A variable which is declared inside a
Enclosed(E) Defined inside enclosing
function which contains another function
functions (Nested
oo
definition with in it, the inner function
function concept)
can also access the variable of the outer
function. This scope is called enclosed Global(G) Defined at the uppermost
scope. level
Built-in(B) Reserved names in built-
ab
4. print a print a 10
Disp 1( )
5. Disp1() print a 10
6. print a Disp( )
w
a module.
Disp() can be even used by Disp1() because
it is also a member of Disp(). (i) Modules contain instructions, processing
logic, and data.
Built-in Scope :
w
[FRT-'22]
(ii) Modules can be separately compiled and
(i) The built-in scope has all the names that are
stored in a library.
pre-loaded into the program scope when
we start the compiler or interpreter. (iii) Modules can be included in a program.
(ii) Any variable or function which is defined (iv) Module segments can be used by invoking
in the modules of a programming language a name and some parameters.
has Built-in or module scope. Consider the (v) Module segments can be used by other
following example. modules.
21
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit I - Chapter 3
3.
Sura’s
programming.
Available at All Leading Bookstores
m
because a small team deals with only a
small part of the entire code. PTA Questions and Answers
(iv) Modular programming allows many
co
programmers to collaborate on the same
1 MARK
application. 1. A variable which is declared inside a function
(v) The code is stored across multiple files.
which contains another function definition :
[PTA-1]
.
(vi) Code is short, simple and easy to
(a) Local (b) Global
understand.
ks
(c) Enclosed (d) Built-in
(vii) Errors can easily be identified, as they are
[Ans. (c) Enclosed]
localized to a subroutine or function.
2. Which are loaded as soon as the library files
(viii) The same code can be used in many
are imported to the program? [PTA-3]
applications.
oo
(a) Built-in scope variables
(ix) The scoping of variables can easily be (b) Enclosed scope variables
controlled. (c) Global scope variables
sum1( ) 2 MARKS
num1:=num1 + 10 1. What are modules? [PTA-4]
sum2( ) Ans. A module is a part of a program. Programs
w
22
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Chapter
Available at All Leading Bookstores
4 ALGORITHMIC STRATEGIES
m
. co
CHAPTER SNAPSHOT
ks
4.1 Introduction to Algorithmic strategies
4.1.1. Characteristics of an Algorithm
4.1.2. Writing an Algorithm
oo
4.1.3. Analysis of Algorithm
4.2 Complexity of an Algorithm
4.2.1. Time Complexity
4.2.2. Space Complexity
ab
[28]
Available at All Leading Bookstores
Algorithmic strategies
possesses which property?
Part - I
(a) Overlapping subproblems
Choose the best answer (1 mark) (b) Optimal substructure
1. The word comes from the name of a Persian
mathematician Abu Ja’far Mohammed ibn-i (c) Memoization
m
Musa al Khowarizmi is called? (d) Greedy
[PTA-6; Aug-2021; May-'22] [Ans. (a) Overlapping subporblems]
(a) Flowchart (b) Flow 10. In dynamic programming, the technique of
co
(c) Algorithm (d) Syntax storing the previously calculated values is
[Ans. (c) Algorithm] called ? [HY-2019]
2. From the following sorting algorithms which
(a) Saving value property
algorithm needs the minimum number of
swaps? [FRT-'22]
(b) Storing value property
.
(a) Bubble sort (b) Insertion sort (c) Memoization
ks
(c) Selection sort (d) All the above (d) Mapping [Ans. (c) Memoization]
[Ans. (c) Selection sort] Part - II
3. Two main measures for the efficiency of an
algorithm are [Mar.-2020]
Answer the following questions
oo
(a) Processor and memory (2 marks)
(b) Complexity and capacity
(c) Time and space (d) Data and space 1. What is an Algorithm? [Mar.-2020; Aug-2021]
[Ans. (c) Time and space] Ans. An algorithm is a finite set of instructions to
ab
5. From the following sorting algorithms which description of the operations principle of a
has the lowest worst case complexity? computer program or other algorithm.
(a) Bubble sort (b) Quick sort
(ii) It uses the structural conventions of a
.s
(c) Merge sort (d) Selection sort normal programming language, but is
[Ans. (c) Merge sort] intended for human reading rather than
6. Which of the following is not a stable sorting machine reading.
w
5.
Sura’s
Available at All Leading Bookstores
m
complexity of algorithms:
(ii) Binary Search
(i) Big O : Big O is often used to describe the
Part - III worst-case of an algorithm.
Answer the following questions
co
(ii) Big Ω : Big Omega is the reverse Big O, if
(3 marks) Bi O is used to describe the upper bound
1. List the characteristics of an algorithm. (worst - case) of a asymptotic function, Big
Ans. (i) Input [Aug-2021; May-'22] Omega is used to describe the lower bound
.
(best-case).
ks
(ii) Output
(iii) Finiteness (iii) Big Θ : When an algorithm has a complexity
(iv) Definiteness with lower bound = upper bound, say that
an algorithm has a complexity O (n log
(v) Effectiveness
oo n) and Ω (n log n), it’s actually has the
(vi) Correctness
complexity Θ (n log n), which means the
(vii) Simplicity running time of that algorithm always falls
(viii) Unambiguous in n log n in the best-case and worst-case.
ab
(ii) Space Complexity : Space complexity sub-problems. So that their results can be
of an algorithm is the amount of memory
required to run to its completion. re-used to complete the process.
w
3. What are the factors that influence time and (iv) Dynamic programming approaches are
space complexity? used to find the solution in optimized way.
For every inner sub problem, dynamic
Ans. (i) Time Factor -Time is measured by
counting the number of key operations like algorithm will try to check the results of
comparisons in the sorting algorithm. the previously solved sub-problems. The
solutions of overlapped sub-problems are
(ii) Space Factor - Space is measured by the
maximum memory space required by the combined in order to get the better solution.
algorithm.
30
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
6
Chapter
CONTROL STRUCTURES
CHAPTER SNAPSHOT
m
6.1 Introduction 6.2.2 Alternative or Branching Statement
co
6.2 Control Structures 6.2.3. Iteration or Looping constructs
6.2.1 Sequential Statement 6.2.4 Jump Statements in Python
.
while True:
Part - I
ks
if i%3 ==0:
Choose the best answer (1 mark) break
1. How many important control structures are print(i,end='')
there in Python? [SRT-'22] i +=1
(a) 3 (b) 4 (c) 5
oo (d) 6
(a) 12 (b) 123 (c) 1234 (d) 124
[Ans. (a) 12]
[Ans. (a) 3] 8. What is the output of the following snippet?
2. elif can be considered to be abbreviation of T=1
[May-'22] while T:
ab
programming? [Aug-2021]
9. Which amongst this is not a jump statement ?
(a) Statements (b) Control (a) for (b) pass
(c) Structure (d) Indentation (c) continue (d) break
[Ans. (d) Indentation] [Ans. (a) for]
.s
4. Which statement is generally used as a 10. Which punctuation should be used in the
placeholder? blank?
(a) continue (b) break if <condition>_
w
2.
Sura’s
Available at All Leading Bookstores
m
if <condition>: Ans. Code :
statements-block 1 n1=int(input(:Enter the first number:"))
else: n2=int(input("Enter the second number:"))
co
statements-block 2 n3=int(input(:Enter the third number:"))
4. Define control structure. [PTA-2] if(n1?=n2)and(n1>=n3):
Ans. A program statement that causes a jump of biggest=n1;
control from one part of the program to another elif(n2>=n1)and (n2>=n3):
.
is called control structure or control statement. biggest=n2
ks
5. Write note on range () in loop. else:
[PTA-2; March-2020; July-'22] biggest=n3
Ans. range() generates a list of values starting from print("The biggest number
start till stop-1. between",n1,",",n2,"and",n3,"is",biggest)
oo
The syntax of range() is as follows: Output :
range (start,stop,[step]) Enter the first number:1
Where, Enter the second number:3
start – refers to the initial value Enter the third number:5
ab
stop – refers to the final value The biggest number between 1,3 and 5 is 5
step – refers to increment value, this is optional
part. 4. Write the syntax of while loop.
[PTA-4; QY-2019; SRT & July-'22]
Part - III Ans. Syntax:
ur
A statements block2]
AB 5. List the differences between break and
ABC continue statements. [HY-2019; May-'22]
w
ABCD
ABCDE Ans. Break Continue
Ans. for i in range (1, 6): The break statement The continue
w
Available at All Leading Bookstores
Control Structures
in sequence
(5 marks)
1. Write a detail note on for loop. Yes
[Govt. MQP-2019; Aug-2021; SRT, May & July-'22] Last item
m
Ans. (i) for loop : for loop is the most comfortable
reached?
loop. It is also an entry check loop. The
condition is checked in the beginning and
co
the body of the loop(statements-block 1)
is executed if it is only True otherwise the No
loop is not executed.
(ii) Syntax: Body of for
.
for counter_variable in sequence:
ks
statements-block 1 Exit loop
[else: # optional block for loop execution
statements-block 2]
Example :
(iii) The counter_variable mentioned in the
oo #Program to illustrate the use of for loop - to
syntax is similar to the control variable
that we used in the for loop of C++ and print single digit even number
the sequence refers to the initial, final for i in range (2,10,2):
and increment value. Usually in Python, print (i, end=' ')
ab
(iv) The syntax of range() is as follows: with suitable example. [HY-2019; Sep-2020]
range (start,stop,[step]) Ans. Nested if..elif...else statement :
Where, (i) When we need to construct a chain of if
start – refers to the initial value statement(s) then 'elif' clause can be used
.s
statements-block n
range (30,3,-3) - will start the range of values
(iii) In the syntax of if..elif..else mentioned
from 30 and end at 6 above, condition-1 is tested if it is true then
range (20) - will consider this value 20 as statements-block1 is executed, otherwise
the end value(or upper limit) the control checks condition-2, if it is true
and starts the range count statements-block2 is executed and even if it
from 0 to 19 (remember fails statements-block n mentioned in else
always range() will work till part is executed.
stop -1 value only)
63
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit II - Chapter 6
Sura’s
Available at All Leading Bookstores
Test
Output 2 :
Enter mark in first subject : 67
false
Expression
of if Enter mark in second subject : 73
Grade : B
True Test 3. Write a program to display all 3 digit odd
false
Body of if
Expression
of elif numbers.
m
True Ans. for a in range (100, 1000):
if a %2==1:
print b
co
Body of else
Body of elif
Output :
if..elif..else statement execution
101, 103, 105, 107 ... .... 997, 999
.
statements to one if..elif…else. 'elif' can table for a given number.
ks
be considered to be abbreviation of 'else if'. Ans. Multiplication table :
In an 'if' statement there is no limit of 'elif '
num = int(input("Enter the number : "))
clause that can be used, but an 'else' clause
if used should be placed at the end. prit("multiplication Table of ", num)
oo for i in range(1,11):
(v) Example : #Program to illustrate the use of
nested if statement print (num, "x", i, " = ", num*i)
Average Grade Output :
Enter the number : 6
ab
Otherwise E 6 × 4 = 24
m1=int (input("Enter mark in first subject : ")) 6 × 5 = 30
m2=int (input("Enter mark in second subject : ")) 6 × 6 = 36
.s
avg= (m1+m2)/2 6 × 7 = 42
if avg>=80: 6 × 8 = 48
print ("Grade : A") 6 × 9 = 54
w
64
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
STRINGS AND
8
Chapter
STRING MANIPULATION
m
CHAPTER SNAPSHOT
8.1 Introduction 8.6 String Formatting Operators
co
8.2 Creating Strings 8.7 Formatting characters
8.3 Accessing characters in a String 8.8 The format( ) function
8.4 Modifying and Deleting Strings 8.9 Built-in String functions
8.5 String Operators 8.10 Membership Operators
.
ks
Evaluation 5. Strings in python:
(a) Changeable (b) Mutable
[Aug-2021]
str1="TamilNadu"
[Ans. (b) [ ]]
print(str1[::–1])
7. What is stride? [PTA-2; July-'22]
(a) Tamilnadu (b) Tmlau
(a) index value of slide operation
(c) udanlimaT (d) udaNlimaT
ur
[Ans. (a) +]
(a) { } (b) < > (c) ++ (d) ^^
4. Defining strings within triple quotes allows [Ans. (a) { }]
creating: [HY-2019] 10. The subscript of a string may be:
(a) Single line Strings (b) Multiline Strings (a) Positive (b) Negative
(c) Double line Strings (d) Multiple Strings (c) Both (a) and (b) (d) Either (a) or (b)
[Ans. (b) Multiline Strings] [Ans. (d) Either (a) or (b)]
[99]
Sura’s
Available at All Leading Bookstores
m
(ii) String is a sequence of Unicode characters
that may be a combination of letters,
(3 marks)
numbers, or special symbols enclosed 1. Write a Python program to display the given
co
within single, double or even triple quotes. pattern. [Govt. MQP-2019]
(iii) Example : COMPUTER
'Welcome to learning Python' COMPUTE
COMPUT
"Welcome to learning Python" COMPU
.
" "Welcome to learning Python" " COMP
ks
2. Do you modify a string in Python? COM
Ans. (i) Yes we can modify the string by the CO
following method. C
(ii) A new string value can be assign to the Ans. str1 = "COMPUTER"
existing string variable.
oo index = len(str1)
(iii) When defining a new string value to the for i in str1:
existing string variable. print (str1[: index])
(iv) Python completely overwrite new string on index – = 1
the existing string.
ab
4. What will be the output of the following (b) swapcase( ) It will >>> str1="tAmiL
python code? [July-'22] change NaDu"
str1 = "School" case of
w
>>> print(str1.
print(str1*3) every swapcase())
Ans. Output : School School School character TaMIl nAdU
5. What is slicing? [PTA-6; Aug-2021] to its
Ans. (i) Slice is a substring of a main string. A opposite
substring can be taken from the original case vice-
string by using [] operator and index or versa.
subscript values.
100
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
m
following operators for string operations. These
4. What is the use of format( )? Give an example. operators are useful to manipulate string.
[HY-2019]
(i) Concatenation (+) : Joining of two or more
Ans. (i) The format( ) function used with strings is strings is called as Concatenation. The plus
co
very versatile and powerful function used (+) operator is used to concatenate strings
for formatting strings. in python.
(ii) The curly braces { } are used as placeholders Example :
or replacement fields which get replaced >>> "welcome" + "Python"
along with format( ) function.
.
'welcomePython'
(iii) Example : (ii) Append (+ =) : Adding more strings at
ks
num1=int (input("Number 1: ")) the end of an existing string is known as
num2=int (input("Number 2: ")) append. The operator += is used to append
print ("The sum of {} and {} is {}". a new string with an existing string.
format(num1,num2,(num1+num2))) Example :
Output :
oo >>> str1="Welcome to "
Number 1: 34 >>> str1+="Learn Python"
Number 2: 54 >>> print (str1)
The sum of 34 and 54 is 88 Welcome to Learn Python
ab
Available at All Leading Bookstores
Chapter PYTHON CLASSES AND
10 OBJECTS
m
co
CHAPTER SNAPSHOT
10.1 Introduction
10.2 Defining classes
10.3 Creating Objects
.
ks
10.4 Accessing Class Members
10.5 Class Methods
10.6 Constructor and Destructor in Python
10.7 Public and Private Data Members
oo
Evaluation 5. A private class variable is prefixed with
(a) __ (b) && (c) ## (d) **
[Ans. (a) __]
ab
Part - I
6. Which of the following method is used as
Choose the best answer (1 mark) destructor? [PTA-1; QY-2019; May-'22]
1. Which of the following are the key features of (a) __init__( ) (b) __dest__( )
(c) __rem__( ) (d) __del__( )
ur
9.
Sura’s
variable?
Available at All Leading Bookstores
m
(a) Constructor (b) Destructor
[PTA-2; SRT-'22]
(c) Initialize (d) Instantiation
[Ans. (d) Instantiation] Ans. (i) Destructor is also a special method gets
executed automatically when an object exit
Part - II
co
from the scope.
Answer the following questions (ii) In Python,_del_() method is used as
(2 marks) destructor.
General format :
1. What is class? [PTA-1]
.
def_del_(self):
ks
Ans. (i) Class is the main building block in Python. <statements>
(ii) Class is a template for the object. Part - III
(iii) Object is a collection of data and function
that act on those data.
Answer the following questions
(3 marks)
(iv) Objects are also called as instances of a
oo 1. What are class members? How do you define it?
class.
[PTA-1; Aug-2021]
2. What is instantiation? [PTA-6; SRT-'22] Ans. Variables defined inside a class are called as “Class
Ans. Once a class is created, next to create an object Variable” and functions are called as “Methods”.
ab
or instance of that class. The process of creating Class variable and methods are together known
object is called as “Class Instantiation”. as members of the class. The class members
Syntax : should be accessed through objects or instance
Object_name = class_name( ) of class. A class can be defined anywhere in a
Python program.
ur
print(self.__num) statement_2
S=Sample() ....................
S.disp() ....................
w
print(S.__num) statement_n
Ans. Output : 2. Write a class with two private class variables
>>> and print the sum using a method.
w
[PTA-2]
10
Ans. Code :
line 7, in <module>
class Sample :
print(S._num)
w
Available at All Leading Bookstores
m
3. Find the error in the following program to get def __init__(self, num):
the given output? print("Constructor of class Sample...")
class Fruits: self.num=num
co
def __init__(self, f1, f2):
print("The value is :", num)
self.f1=f1
self.f2=f2 S=Sample(10)
def display(self): Destructor :
.
print("Fruit 1 = %s, Fruit 2 = %s"
ks
(i) Destructor is also a special method gets
%(self.f1, self.f2)) executed automatically when an object exit
F = Fruits ('Apple', 'Mango') from the scope.
del F.display
(ii) In Python, __del__() method is used as
F.display()
oo
destructor.
Output :
Fruit 1 = Apple, Fruit 2 = Mango General format of constructor :
Ans. In line No.8, del F.display will not come. def__del__(self):
ab
class Sample:
def display(self):
num=0
print("Good Morning ", self.__name)
obj=Greeting('Bindu Madhavan') def __init__(self, var):
.s
5. How to define constructor and destructor in print("The object value is = ", var)
Python? [PTA-4; Mar-2020; Sep-2020]
print("The value of class variable is=
Ans. Constructor :
w
", Sample.num)
(i) Constructor is the special function that
is automatically executed when an object def __del__(self):
of a class is created. In Python, there is a
w
Sample.num-=1
special function called “init” which act as a
print("Object with value %d is exit
Constructor.
from the scope"%self.var)
(ii) It must begin and end with double
underscore. S1=Sample(15)
(iii) Constructor function will automatically S2=Sample(35)
executed when an object of a class is created. S3=Sample(45)
141
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10
Sura’s
Available at All Leading Bookstores
m
Ans. Code : self.m1=0
stationary = {} self.m2=0
self.tot=0
print("\n1.Add Item \n2. Delete item \n3.Exit")
def gdata(self):
co
ch=int(input("\nEnter your choice:")) self.name = input("Enter your name")
while(ch==1) or (ch==2): self.m1 = int(input("Enter marks 1"))
if(ch==1) self.m2 = int(input("Enter marks 2"))
n=int(input("\nEnter the Number of self.tot = self.m1 + self.m2
.
def disp(self):
Items to be added in the Dictionary:"))
ks
print(self.name)
for i in range(n): print(self.m1)
item=input("\nEnter an Item Name:") print(self.m2)
brand=input("\nEnter the Brand Name:") print(self.tot)
stationary[item]=brand
oo mlist = []
st = stud()
print(stationary) st. gdata()
elif(ch==2): mlist.append(st)
ritem=input("\nEnter the item to be for x in mlist :
ab
2. Delete item
Ans. Class Tr:
3. Exit def__init__(self, a, b, c):
Enter your choice : 1 self.a = float(a)
w
Available at All Leading Bookstores
m
self.dist 1 =int(input("Enter distance 1"))
Enter distance 2 : 75
sefl.dist 2 =int(input("Enter distance 2"))
Do you want to continue ..y
def disp(self):
print("distance 1", self.dist 1) 1. Accept
co
print("distance 2", self.dist 2) 2. Display
def add(self): 3. Add
print("Total distance", self.dist 1 + self.dist 4. Sub
2) Enter your choice : 4
.
def sub(self): Subtracted distance : 25
ks
print("Subtracted distance", self.dist 1-self. Do you want to continue .. N
dist 2)
d=Dist() PTA Questions and Answers
choi = "y"
while(choi =="y"):
oo 1 MARK
print("1. accept\n2. Display \n3. Total \n4. 1. In Python the class method must have which
Subtract")
named argument as first argument? [PTA-3]
ch = int(input("Enter your choice"))
(a) self (b) rec
if(ch==1):
ab
object_name = class_name()
Enter distance 2 : 75
Do you want to continue .. y Note that the class instantiation uses function
1. Accept notation. ie.class_name with.
2. Display 2. Write the general format of slicing operation.
3. Add [PTA-6]
4. Subtract
Ans. General format of slice operation:
Enter your choice : 3
Total distances : 175 str[start:end]
143
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10
1.
Sura’s
Available at All Leading Bookstores
m
(ii) A variable prefixed with double underscore 'o', 'O', 'u', 'U')):
becomes private in nature. These variables self.vowels+=1
can be accessed only within the class. def count_consonants(self):
co
v=('A', 'a', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U')
5 MARKS
for ch in self.string:
1. Find the output of the following Python code if ch not in v and ch.isalpha():
[PTA-1] self.consonants+=1
.
class Sample: def count_space(self):
num=0
ks
for ch in self.string:
def __init__(self, var): if (ch==" "):
Sample.num+=1 self.spaces+=1
self.var=var def execute(self):
print("The object value is = ", var)
oo self.count_upper()
print("The count of object created self.count_lower()
= ", Sample.num) self.count_vowels()
S1=Sample(15) self.count_consonants()
S2=Sample(35) self.count_space()
ab
2.
Python code? [PTA-2] print("%d Consonants"%self.
class String consonants)
def__init__(self): print("%d Spaces"%self.spaces)
w
self.uppercase=0 S = String()
self.lowercase=0 S.getstr()
self.vowels=0 S.execute()
w
self.consonants=0 S.display()
self.spaces=0 Ans. Output :
w
144
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
m
print("Good Morning", self.__name)
Class circle( ) obj=Greeting('Tamil Nadu')
pi=3.14 obj.display()
def__init__(self, radius):
co
Ans. Good Morning Tamil Nadu
self=radius
2. What is Constructor? [QY-2019]
DEF area(SELF):
Ans. Constructor is the special function that is
Return automatically executed when an object of a class
Circle.pi + (self.radius * 2)
.
is created. In Python, there is a special function
ks
Def circumference (self): called “init” which act as a Constructor. It must
Return 2*circle.pi * self.radius begin and end with double underscore. This
r = input("Enter radius= ") function will act as an ordinary function; but only
difference is, it is executed automatically when
c = circle(r)
the object is created. This constructor function
print "The Area: ", c.area( )
oo
can be defined with or without arguments. This
print("The circumference=", c) method is used to initialize the class variables.
Ans. Class circle: General format of __init__ method (Constructor
pi=3.14 function)
ab
r=int(input("Enter Radius:"))
c = circle(r) else:
print(num," is Odd number")
print("The Area= ", c.area( ))
n=Odd_Even()
w
145
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10
5.
Sura’s
Available at All Leading Bookstores
m
obj=Hosting("Python Programming") x, y = 10, 20 # class variables
obj.display() In the above code, name of the class is Sample
Ans. Output : Welcome to Python Programming. and it has two variables x and y having the
co
initial value 10 and 20 respectively. To
6. What will be the output of the following
access the values defined inside the class,
program? [SRT-'22]
you need an object or instance of the class.
class stud:
m1, m2, m3 = 45, 91, 71 2. What will be the output of the following
.
def process(self) : program? [SRT-'22]
ks
sum = stud.m1 + stud.m2 + stud.m3 Class Sample :
avg = sum/3 num = 0
print("Total Marks = ", sum) def _ _init_ _(self, var):
print("Average Marks = ", avg) Sample.num + = 1
return
oo self.var = var
s. stud( ) print("The object value is = ", var)
s. process( ) print("The count of object created = ",
Ans. Total Marks = 207 Sample.num)
ab
[QY-2019]
(or) The count of object created = 1
The object value is = 35
How to define a class in Python? Explain with
example. [SRT-'22] The count of object created = 2
.s
Ans. (i) In Python, a class is defined by using the The object value is = 45
keyword class. Every class has a unique The count of object created = 3
name followed by a colon ( : ).
w
146
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
4. In Python, every class name followed by 12. Which argument doesn’t need a value when we
call the method?
m
(a) ; (b) : (c) : : (d) .
(a) this (b) self
[Ans. (b) :] (c) var (d) first
5. Which of the following with a valid class [Ans. (b) self]
co
definition? 13. Which of the following argument values
(a) Class classname () statement_1 automatically by python?
(b) Class classname : : statement_1 (a) self (b) this
(c) Class classname statement_1 (c) class (d) object
[Ans. (a) self]
.
(d) Class classname statement_1
14. How many argument can be taken by Python
ks
[Ans. (c) Class classname statement_1]
method even when a method is defined with
6. Which of the following is valid syntax for one argument?
crating objects? (a) 1 (b) 3 (c) 2 (d) 4
(a) objectname = classname () [Ans. (c) 2]
(b) objectname : classname ()
oo 15. Which of the following is automatically
(c) objectname = classname executed when an object of a class is created?
(d) classname = Objectname () (a) constructor (b) destructor
[Ans. (c) objectname = classname] (c) class (d) members
ab
scope?
10. Write the output for the following (a) Destructor (b) Constructor
class test (c) Class (d) Object
x, y = 10, 5 [Ans. (a) Destructor]
s = test () 20. By default, the class variables are
print (s. x + s. y) (a) Private (b) Public
(a) 10 (b) 5 (c) 15 (d) 105 (c) Protected (d) Method
[Ans. (c) 15] [Ans. (b) Public]
147
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10
Sura’s
Available at All Leading Bookstores
m
(c) Private (d) None of these (a) classnam, : (b) classname, .
[Ans. (d) None of these] (c) :, classname
(d) classname, objectname
Choose and filling the blanks
co
[Ans. (b) classname, .]
1. ____ and ___ are the key features of object 10. Constructor must begin and with double
oriented programming. ______
(a) List and tuples (a) Colon (b) Semicolon
(b) Set and dictionary
.
(c) Dot (d) Underscore
(c) Classes and objects [Ans. (d) Underscore]
ks
(d) Variables and methods
11. In Python, _____ method is used as destructor.
[Ans. (c) Classes and objects]
(a) - - init - - () (b) - - des - - ()
2. ____ is the main building block in python. (c) - - del - - ()
(a) Objects (b) Methods
oo (d) - - destructor - - () [Ans. (b) - - des - - ()]
(c) Constructors (d) Class
12. A variable prefixed with _____ become private
[Ans. (d) Class] in nature.
3. Class is a template for the _____ (a) double underscore (b) double colon
ab
(a) Method (b) Members (c) double dot (d) double hyphen
(c) Object (d) Destructor [Ans. (a) double underscore]
[Ans. (c) Object] Choose the correct statement
4. ______ may be a variable declaration, decision 1. (a) objectname.classmember()
control, loop or even a function definition.
ur
(b) objectname.classmember
(a) Class members (c) objectname().classmember
(b) Class instantiation (d) objectname : classmember
(c) Class method [Ans. (b) objectname.classmember]
.s
148
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
m
print("The value is :", num)
[Ans. (d) i and iii]
S=Sample(10)
2. (i) C onstructor executed automatically when
Short Answers 3 MARKS
co
the object is created
(ii) In Python, “init” which act as a destructor. 1. Write a note on object.
(iii) In Python, constructor can be defined only Ans. (i) Object is a collection of data and function
with arguments. that act on those data. Class is a template
.
(iv) Construct is used to initialize the class for the object.
ks
variables.
(ii) According to the concept of Object
(a) i and iii (b) ii and iv Oriented Programming, objects are also
(c) iii, iv and ii (d) ii and iii called as instances of a class.
[Ans. (d) ii and iii]
(iii) In Python, everything is an object. For
oo
Very Short Answers 2 MARKS example, all integer variables that we use
1. Write the general form of declaring class in in our program is an object of class int.
Python. Similarly all string variables are also object
Ans. In Python, a class is defined by using the keyword
of class string.
ab
class. Every class has a unique name followed by 2. Write a note on self argument used in python
a colon ( : ). class function.
Syntax : Ans. (i) Python class function or Method is very
class class_name: similar to ordinary function with a small
ur
(ii) Object – name = class_member argument it will take it as two arguments ie.
3. Differentiate python class function and self and the defined argument.
ordinary function.
w
Ans. Python class function or method is very similar 3. Explain the working of the following program.
to ordinary function with a small difference. class Sample:
The class method must have the first argument def __init__(self, num):
named as self. print("Constructor of class
4. Name the function which acts as a constructor Sample...")
and destructor. self.num=num
Ans. Constructor -(- - init - - ( )) print("The value is :", num)
Destructor -(- - del - - ( )) S=Sample(10)
149
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit III - Chapter 10
Sura’s
Ans. (i)
Available at All Leading Bookstores
m
passed along with the given string. Class sample:
(ii) The above constructor gets executed x, y = 10, 20
automatically, when an object S is created s = sample ()
co
with actual parameter 10. Thus, the Python print (s. x + s. y)
displays the following output. 1. What does sample denotes?
(iii) Constructor of class Sample... 2. What does x, y denotes?
The value is : 10 3. What does s denotes?
.
Class variable defined within constructor Ans. 1. It denotes class name
ks
keep count of number of objects created 2. x, y is a class variables of the class
with the class. 3. S is an object created to access the members
4. Write a python program to find total and of the class
average marks using class. Long Answers 5 MARKS
oo
Ans. class Student: 1. Write a program to check and print if the given
number is negative or positive using class.
mark1, mark2, mark3 = 45, 91, 71
Ans. class test:
#class variable def check (self, num)
ab
S.process() self.bookname=""
self.author=""
5. Fill up the blanks in the following program to def getdata(self):
w
150
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
m
elif(resp==2): def print_bill(self):
for x in book:
x.display() total_price = 0
else:
co
for x in range(self.p):
print("Invalid input....")
ch = input("Do you want continue....") q=int(input("Enter the quantify for
3. Write a program to store product and its cost the product code %d : "%self.__
price. Display all the available products and prod_code[x]))
.
prompt to enter quantity of all the products.
ks
self.__prod_quant.append(q)
Finally generate a bill which displays the total
amount to be paid. total_price = total_price +self.__cost_
Ans. class MyStore: price[x]*self.__prod_quant[x]
__prod_code=[]
oo print(" Invoice Receipt ")
__prod_name=[]
__cost_price=[] print("-------------------------------------")
__prod_quant=[] print("Product Code\t Product Name\t
def getdata(self): Cost Price\t Quantity \t Total Amount")
ab
print("Stock in Stores")
print("-------------------------------------")
print("-------------------------------------")
print("Product Code \t Product Name \t print(" Total Amount = ", total_price)
w
Cost Price")
w
151
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
Chapter
PYTHON AND CSV FILES
13
m
co
CHAPTER SNAPSHOT
13.1 Introduction
.
13.2 Difference between CSV and XLS file formats
ks
13.3 Purpose of CSV File
13.4 Creating a CSV file using Notepad (or any text editor)
13.4.1 Creating CSV Normal File
13.4.2 Creating CSV File That contains Comma With Data
oo
13.4.3 Creating CSV File That contains Double Quotes With Data
13.4.4 Rules to be followed to format data in a CSV file
13.5 Create a CSV File using Microsoft Excel
13.5.1 Microsoft Excel to open a CSV file
ab
13.6.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
[192]
Available at All Leading Bookstores
Evaluation chennai,mylapore
mumbai,andheri
m
(a) Flat File (b) 3D File
mumbai,andheri
(c) String File (d) Random File
[Ans. (b) mumbai,andheri]
[Ans. (a) Flat File]
8. Which of the following creates an object which
co
2. The expansion of CRLF is maps data to a dictionary? [PTA-1]
[Govt. MQP-2019; May-'22]
(a) listreader() (b) reader()
(a) Control Return and Line Feed
(c) tuplereader() (d) DictReader ()
(b) Carriage Return and Form Feed
[Ans. (d) DictReader ()]
.
(c) Control Router and Line Feed
ks
(d) Carriage Return and Line Feed 9. Making some changes in the data of the
[Ans. (d) Carriage Return and Line Feed] existing file or adding more data is called
3. Which of the following module is provided by (a) Editing (b) Appending
Python to do several operations on the CSV (c) Modification (d) Alteration
files?
oo
[Ans. (c) Modification ]
(a) py (b) xls (c) csv (d) os
[Ans. (c) csv] 10. What will be written inside the file test.csv
using the following program?
4. Which of the following mode is used when
ab
Q Quarterly,
6. Which of the following is a string used to
H Halfyearly
terminate lines produced by writer()method
[Ans. (d) Exam,
of csv module?
Quarterly,
w
7. What is the output of the following program? Answer the following questions
import csv (2 marks)
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
1. What is CSV File? [PTA-3; Aug-2021; May-'22]
next(d)
Ans. (i) A CSV file is a human readable text file
for row in d:
where each line has a number of fields,
print(row)
separated by commas or some other
if the file called “city.csv” contain the following
delimiter.
details
193
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit IV - Chapter 13
Sura’s
Available at All Leading Bookstores
m
(a) Use the csv module’s reader function 2. Write a Python program to modify an existing
file. [July-'22]
(b) Use the DictReader class.
Ans. import csv
co
3. Mention the default modes of the File.
row = [‘3’, ‘Meena’,’Bangalore’]
Ans. (i) The default is reading ('r') in text mode.
with open(‘student.csv’, ‘r’) as readFile:
(ii)
In this mode, while reading from the file
the data would be in the format of strings. reader = csv.reader(readFile)
.
lines = list(reader) # list()- to store each
ks
4. What is use of next() function?
row of data as a list
Ans. (i) "next()" command is used to avoid or skip
the first row or row heading. lines[3] = row
(ii) Example : While sorting the row heading with open(‘student.csv’, ‘w’) as writeFile:
oo
is also get sorted, to avoid that the first is # returns the writer object which converts the user
skipped using next(). data with delimiter
(iii) Then the list is sorted and displayed. writer = csv.writer(writeFile)
ab
5. How will you sort more than one column from #writerows()method writes multiple rows to a csv
a csv file? Give an example statement. file
Ans. To sort by more than one column you can use writer.writerows(lines)
itemgetter with multiple indices: operator
readFile.close()
ur
.itemgetter (1,2).
Syntax : writeFile.close()
sortedlist = sorted(data, key=operator.itemget 3. Write a Python program to read a CSV file
.s
194
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Sura’s
Available at All Leading Bookstores
m
Importing C++
Programs in Python
co
Chapter
14
.
ks
oo
CHAPTER SNAPSHOT
14.1 Introduction
14.2 Scripting Language
ab
14.6.1 Module
14.6.2 How to import modules in Python?
14.7 Python program Executing C++ Program using control statement
w
[210]
Available at All Leading Bookstores
m
language? 9. Which of the following can be used for
(a) JavaScript (b) PHP processing text, numbers, images, and
(c) Perl (d) HTML scientific data?
co
[Ans. (d) HTML] (a) HTML (b) C
(c) C++ (d) PYTHON
2. Importing C++ program in a Python program
[Ans. (d) PYTHON]
is called [HY-2019]
(a) wrapping (b) Downloading 10. What does __name__ contains ? [PTA-6]
.
(c) Interconnecting (d) Parsing (a) c++ filename (c) main() name
ks
[Ans. (a) wrapping] (c) python filename (d) os module name
[Ans. (C) python filename]
3. The expansion of API is
(a) Application Programming Interpreter
Part - II
(b) Application Programming Interface Answer the following questions
oo
(c) Application Performing Interface (2 marks)
(d) Application Programming Interlink 1. What is the theoretical difference between
[Ans. (b) Application Programming Scripting language and other programming
Interface] language? [Aug-2021]
ab
4. A framework for interfacing Python and C++ is Ans. (i) The theoretical difference between the two
[Mar.-2020; May-'22] is that scripting languages do not require the
(a) Ctypes (b) SWIG compilation step and are rather interpreted.
(c) Cython (d) Boost (ii) For example, normally, a C++ program
ur
(a) OS module (b) sys module (ii) Compiler reads Interpreter reads
(c) csv module (d) getopt module entire program for single statement
[Ans. (a) OS module] compilation. at a time for
interpretation.
7. getopt() will return an empty array if there is (iii) Error deduction is Error deduction is
no error in splitting strings to [July-'22] difficult. easy.
(a) argv variable (b) opt variable (iv) Comparatively faster. Slower.
(c) args variable (d) ifile variable (v) Example : C++ Example : Python
[Ans. (c) args variable]
211
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit V - Chapter 14
3.
Sura’s
Available at All Leading Bookstores
m
Ans. (i) The use of modules to break down large files, used in compiling and linking the
programs into small manageable and code of C, C++ and FORTRAN to be run
organized files. on Windows Operating System.
co
(ii) Modules provide reusability of code. Define (ii) MinGw-W64 (version of MinGW) is the
our most used functions in a module best compiler for C++ on Windows. To
and import it, instead of copying their compile and execute the C++ program, you
definitions into different programs. need ‘g++’ for Windows. MinGW allows
.
5. What is the use of cd command. Give an to compile and execute C++ program
ks
example. dynamically through Python program
Ans. ‘cd’ command refers to change directory and using g++.
absolute path refers to the complete path where (iii) Python program that contains the C++
python is installed.
oo coding can be executed through either by
(Eg) “cd:\>cd c:\program files\open office 4\ using command prompt or by using run
program”
terminal.
Part - III 4. Identify the module, operator, definition name
ab
[May-'22]
(i) an "interpreted" "compiled" language
language Ans. sys.argv is the list of command-line arguments
Python is a C++ is compiled passed to the Python program. argv contains
w
(ii) dynamic-typed statically typed all the items that come along via the command-
language language line input, it's basically an array holding the
Data type is not Data type is required command-line arguments of the program.
w
212
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
m
you to interface with the Windows
(iii) Python runs through an interpreter. operating system where Python is running
(iv) Python code tends to be 5 to 10 times on.
shorter than that written in C++. os.system():
co
(v) In Python, there is no need to declare types (i) Execute the C++ compiling command (a
explicitly. string contains Unix, C command which
(vi) In Python, a function may accept an
also supports C++ command) in the shell
(Here it is Command Window).
argument of any type, and return multiple
.
(ii) For Example to compile C++ program g++
values without any kind of declaration
ks
compiler should be invoked.
beforehand.
(iv) Command : os.system (‘g++’ + <varaiable_
2. Explain each word of the following command name1> ‘-<mode>’ + <variable_name2>
Python <filename.py> -<i> <C++ filename
(i) os.system:- function system() defined
without cpp extension> [May-'22]
oo
Ans. Python <filename.py> -i <C++ filename without
in os module to interact
with the operating system
cpp extension>
(ii) g++:- General compiler to
where,
compile C++ program
Python Keyword to execute the under Windows
ab
string format.
-i input mode (iv) mode:- To specify input or output
C++ filename without Name of C++ file to be mode. Here it is o prefixed
cpp extension compiled and executed with hyphen.
.s
all the items that come along via the command- enable command-line argument parsing.
line input, it's basically a list holding the (iii) Python getopt.getopt method :
(i) This method parses command-line options
command-line arguments of the program.
and parameter list. Following is the syntax
(ii) To use sys.argv, import sys should be
for this method −
used. The first argument, sys.argv[0]
(ii) <opts>,<args>=getopt.getopt(argv, options,
contains the name of the python program
(example pali.py) and sys.argv [1]is the next [long_options])
argument passed to the program (here it is ■ argv - This is the argument list
213
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit V - Chapter 14
Sura’s
Available at All Leading Bookstores
m
recognize as, for input or for output, enable command-line argument parsing.
with options (like 'i' or 'o') that getopt.getopt method : This method parses
command-line options and parameter list.
followed by a colon (:).
Following is the syntax for this method −
co
Here colon is used to denote the <opts>,<args>=getopt.getopt(argv, options,
mode. [long_options])
■ long_options - This contains a list of Here is the detail of the parameters −
strings. Argument of Long options (i) argv : This is the argument list of values
.
should be followed by an equal sign to be parsed (splited). In our program the
ks
('='). complete command will be passed as a list.
■ In our program the C++ file name (ii) options : This is string of option letters that
along with its path will be passed as the Python program recognize as, for input
string and ‘i’ i will be also passed to or for output, with options (like ‘i’ or ‘o’)
oo
indicate it as the input file. that followed by a colon (:). Here colon is
(iv) getopt() method returns value consisting used to denote the mode.
of two elements. (iii) long_options : This contains a list of
(v) Each of these values are stored separately strings. Argument of Long options should
be followed by an equal sign ('='). In our
ab
of C++ file.
(viii) In our examples since the entire command opts, args = getopt.getopt (argv, "i:",['ifile='])
line commands are parsed and no leftover where opts contains [('-i', 'c:\\pyprg\\p4')]
w
214
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
m
following c++ coding
void Readno(int); to accept roll number and
#include <iostream> assign to Rno
using namespace std; void Writeno(); To display Rno.
co
int main() The class Test is derived Publically from the
Student class contains the following details
{ cout<<“WELCOME”;
Protected member
return(0);
Mark1 float
}
.
Mark2 float
The above C++ program is saved in a file Public members
ks
welcome.cpp void Readmark(float, float); To accept mark1
Ans. #Now select File→New in Notepad and type the and mark2
Python program as main.py void Writemark(); To display the marks
Create a class called Sports with the following
oo
# Program that compiles and executes a .cpp file detail
# Python main.py -i welcome Protected members
import sys, os, getopt score integer
def main(argv): Public members
ab
print("Compiling " + cpp_file) Save the C++ program in a file called hybrid.
Write a python program to execute the
os.system('g++ ' + cpp_file + ' -o ' + exe_ file) hybrid.cpp
w
215
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Unit V - Chapter 14
Sura’s
Available at All Leading Bookstores
m
public: exe_file="
void readmark(float m1, float m2) opts, args = getopt.getopt(argv, "i:",
{ [ifile='])
co
mark1 = m1; for o, a in opts:
mark2 = m2; if o, a in opts:
} cpp_file=a+'.cpp'
void writemark() exe_file=a+'.exe'
{ run(cpp_file, exe_file)
.
cout<<"\n mark1"<<mark1; def run(cpp_file, exe_file)
ks
cout<<"\n mark2"<<mark2;
print("Compiling"+cpp_file)
}};
class sports os.system('g++'+ cpp_file + '-o'+ exe_file)
{ print("Running" + exe_file)
protected: print("------------------")
int score;
oo print
public: os.system(exe_file)
void readscore(int s) print
{ if__name__=='__main__':
ab
score = s; main(sys.argv[1:])
} Output :
void writescore() Rollno : 5
{
Mark1 : 100
cout<<"SCORE:"<<score;
Mark2 : 100
ur
}};
class result : public test, public sports TOTAL MARKS : 200
{ SCORE : 200
private: 2. Write a C++ program to print boundary
.s
{
total = mark1 + mark2; Ans. Select File → New in Notepad and type the C++
cout<<"TOTAL MARKS: "<<total; program.
}}; #include<iostream>
w
216
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
m
int main()
(a) __name__ (b) __init__
{
(c) __del__ (d) __def__
int a[4][MAX] = { {1,2,3,4}, {5,6,7,8},
[Ans. (a) __name__]
co
{1,2,3,4}, {5,6,7,8}};
print Boundary(a,4,4); 2. _______ is a built-in variable which evaluates
return 0; to the name of the current module. [PTA-4]
} (a) __name__ (b) __main__
.
save it as Border.cpp (c) __mode__ (d) __init__
ks
open a New notepad file and type the python [Ans. (a) __name__]
program to execute border.cpp Government Exam Questions and Answers
#python border.py -i border.cpp oo
import sys,os,getopt 1 MARK
def main(argv):
1. Which of the following is not a scripting
cpp_file ="
exe_file =" language? [Sep-2020]
(a) Ruby (b) DBMS
ab
print
1. Which of the following are general purpose
os.system(exe_file)
programming language?
print (a) Python (b) C++
w
217
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
m
(a) Python –i <filename.Py> <C++ filename>
[Ans. (d) a and b]
(b) Python <filename – py> <C++ filename> -i
29. The mode ‘i’/’o’ parses each values of the
(c) Python <C++ filename> -i <filename.py>
co
command line and pass as argument to the list
(d) Python <filename.py> -i <C++ filename> called
[Ans. (d) Python <filename.py> -i <C++ (a) Args (b) Opts
filename>] (c) Sys (d) Argv
.
21. In the command python <filename.py> - i [Ans. (b) Opts]
ks
<C++ filename> where i denotes. 30. Which of the following definition invoke the
(a) Information (b) Input mode ‘g++’ compiler and creates the exe file?
(c) ios (d) Interpreter (a) Main (b) Name
[Ans. (b) Input mode]
oo (c) Run (d) System
[Ans. (c) Run]
22. Which of the following is not a python module? Match the following
(a) OS (b) Sys 1. 1 PHP Interface with C
(c) Tel (d) Getopt
ab
219
[email protected] Ph: 8124201000 / 8124301000
www.kalvinesan.com
This is Only for Sample, Full Book Order Online or
Available at All Leading Bookstores
12th
STD
INSTANT SUPPLEMENTARY EXAM - JULY 2022
Reg. No.
Instructions :
m
1) Check the question paper for fairness of printing. If there is any lack of fairness, inform the Hall
Supervisor immediately.
2) Use Blue or Black ink to write and underline and pencil to draw diagrams
co
PART - I
Note : (i) Answer all the questions. (15×1=15)
(ii) Choose the most appropriate answer from the given four alternatives and write the option code and
the corresponding answer.
.
ks
1. Which of the following is a unit of code that is 9. What will be result of the following Python code
often defined within a greater structure? S = [x**2 for x in range (5)]
(a) Subroutines (b) Function print (S)
(c) Files (d) Modules (a) [0, 1, 2, 4, 5] (b) [0, 1, 4, 9, 16]
2.
oo
Which of the following functions build the (c) [0, 1, 4, 9, 16, 25] (d) [1, 4, 9, 16, 25]
abstract data type? 10. Class members are accessed through which
(a) Constructors (b) Destructors operator?
(c) Recursive (d) Nested (a) & (b) . (c) # (d) %
11. A table is known as :
ab
4. Which of the following shortcut is used to create (c) DELETE ALL (d) ALTER TABLE
new Python Program? 13. Which of the following mode is used when
(a) Ctrl + C (b) Ctrl + F dealing with non-text files like image or exe files?
(c) Ctrl + B (d) Ctrl + N (a) Text mode (b) Binary mode
.s
5. ________ is used to print more than one item (c) xls mode (d) CSV mode
on a single line. 14. getopt () will return an empty array if there is no
(a) Semicolon (;) (b) Dollar ($) error in splitting strings to :
w
(c) Comma (,) (d) Colon (:) (a) argv variable (b) opt variable
(c) args variable (d) ifile variable
6. Which is the most Comfortable loop?
15. The function that returns the largest value of the
w
252 Sura’s 12th Std - Computer Science Instant Supplementary Exam - July 2022 Question Paper with Answers
20. What is set in Python? 37. (a) Write the different types of constraints and
21. Mention few examples of Database Management their functions?
System. (OR)
22. Differentiate compiler and interpreter. (b) Explain the characteristics of DBMS.
23. Which method is used to fetch all rows from the 38. (a) Write the different methods to read a file in
database table? Python.
24. What will be the output of the following code? (OR)
m
Str1 = "School"
(b) What is the purpose of range ( )? Explain
print (str1*3) with an example.
PART - III
co
Note : Answer any six questions. Question No. 33 is
compulsory. 6 × 3 = 18 ANSWER
25. Write the syntax of 'while' loop. PART - I
26. Write the basic rules for global keyword in 1. (b) Function
.
python. 2. (a) Constructors
ks
27. Identify the module, operator, definition name 3. (a) Local Scope
for the following: 4. (d) Ctrl + N
welcome.display() 5. (c) Comma (,)
28. Mention the difference between fetchone ( ) and 6. (c) for
fetchmany ( ).
oo 7. (d) def
29. Write a python program to modify an existing
file. 8. (d) third argument of slice operation
30. Write a SQL statement to modify the student 9. (b) [0, 1, 4, 9, 16]
table structure by adding a new field. 10. (b) .
ab
31. Write a note on open ( ) function of Python. What 11. (c) Relation
are the difference between its two methods? 12. (a) DROP
32. List the general types of data visualization. 13. (b) Binary mode
33. What is the output of the following program? 14. (c) args variable
ur
class Greeting :
def _ init _ (selt, name) : 15. (a) MAX ( )
self._ name = name PART - II
def display (self) :
16.
.s
PART - IV
(i) Constructors are Selectors are
Note : Answer all the questions: 5 × 5 = 25 functions that functions that retrieve
34. (a) Discuss about linear search algorithm. build the abstract information from the
w