5mark New
5mark New
fi
fi
on
on
on
on
C
C
(iv) Here, the result of inc) will change every
time the value of'y get changed inside
if
PART- IV
ANSWER THE FOLLOWING QUESTIONS
ey
the function definition.
l
l
(5 MARKs)
ia
tia
tia
tia
() Hence, the side effect of inc () function
is changing the data of the external
nt
en
en
en
variable 'y. on [PTA-2]
de
fid
fid
fid
4. Differentiate pure and impure function. (i) Parameter without Type
(ii) Parameter with Type
on
on
on
on
Ans. [PTA-3,6]
Ans. Parameters (and arguments) : Parameters
S. No. Pure Impure are the variables in a function definition and
C
C
() 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 () Parameter without Type : Let us see an
on its arguments not solely depend example of a function, definition:
onfider
l
l
)
(requires: b>=0
ia
tia
tia
tia
passed. on its arguments
(returns: a to the power of b)
nt
passed.
en
en
en
If you call the pure let rec poW a b:=
(ii) If you call the
de
if b=0 then 1
fid
fid
fid
functions with impure functions
same else a pow a (b -1)
the set of with the same set
on
on
on
on
In the above function definition variable
arguments, you will of arguments,
always get the same you might get the
B is the parameter and the value which is
C
C
passed to the variable 'B is the argument.
return values. different return The precondition (requires) and
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:
l
l
ia
tia
tia
tia
For example, (data types). Some language compiler
nt
en
en
random(), Date().
problem algorithmically, but some require
de
id
id
the type to be mentioned.
the arguments the arguments
f
f
which are passed to which are passed In the above function definition if
on
on
on
on
them to them expression can return l in the then branch,
by the typing rule the entire if expression
C
C
5. What happens if you modify a variable outside has type int.
the function? Give an example.
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,
l
ia
ia
ia
For example :
let y: = 0 lential multiplied with another expresion using
nt
t
en
en
en
fid
fid
y:=y+ X;
return (y) fid? the same function definition with types
on
on
on
on
time if the value of'y get changed inside the (returns: a to the power of b)
function definition. Hence, the side efect 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)
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
When we write the type annotations for (iv) The above function square is a pure function
'a' and 'b' the parentheses are mandatory. because it will not give different results for
Generally we can leave out these Same input.
annotations, because it's simpler to let the There are various theoretical advantages of
l
l
ia
tia
tia
tia
compiler infer them. having pure functions. One advantage is
that if a function is pure, then if it is called
nt
en
en
en
several times with the same arguments,
write down types. This is useful on
de
fid
fid
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;
on
on
on
on
Explicitly annotating the types can help
with debugging such an error message. ifi <strlen (s) then
C
C
-- 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
time and strlen needs to iterate over the
ifb<>0then gcd b (a mod b) else return a whole of 's. If the compiler is smart enough
ide
l
l
ia
tia
tia
tia
i) Name of the function to work out that strlen is a pure function
nt
Identify the statement which tells it is a and that 's is not updated in the loop, then
en
en
en
ii)
it can remove the redundant extra calls to
de
recursive function
fid
fid
fid
ii) Name of the argument variable strlen and make the loop to execute only
iv) Statement which invoke the function
one time.
on
on
on
on
recursively (vii) From these what we can understand, strlen
is a pure function because the function
C
C
v) Statement which terminates the recursion
takes one variable as a parameter, and
Ans. (i) gcd accesses it to find its length. This function
(ii) let rec gcd
reads external memory but does not
(ii) a, b Ttial change it, and the value returned derives
l
l
gcdb (a mod b) from the external memory accessed.
ia
tia
tia
tia
(iv)
return a Impure functions :
nt
(V)
en
en
en
) The variables used inside the function may
de
3. Explain with example Pure and impure cause side effects though the functions
id
id
id
functions. which are not passed with any arguments.
f
f
Ans. Pure functions : In such cases the function is called impure
on
on
on
on
() Pure functions are functions which will function.
give exact result when the same arguments
C
C
(ii) When a function depends on variables or
are passed. functions outside of its definition block,
you can never be sure that the function
(i) For example the mathematical function sin
(0) always results 0. This means that every will behave the same every time its called.
time you call the function with the same For example the mathematical function
l
ia
ia
ia
t
en
en
en
let a := random()
it should not have any external variable
fider
fid
fid
fid
on
on
on
variable.
Let us see an example else
Cor
C
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.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
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
Ans. Interface :
accelerator to get the desired behaviour.
An interface is a set of action that an object
l
l
() Here the accelerator is the interface
ia
tia
tia
tia
can do. For example when you press a light
between the driver (the calling invoking
nt
en
en
en
object) and the engine (the called object).
cared how it splashed the light. In Object
de
fid
fid
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
on
on
on
on
It'swhere fuel, air, pressure, and electricity
interface. come together to create the power to move
C
C
(i) In our example, anything that "ACTS the vehicle.
LIKE" 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
l
l
HANDS ON PRACTICE
ia
tia
tia
tia
class of TYPE T (whatever the interface is)
must have functions called X, Y, Z, etc.
nt
en
en
en
(iii) A class declaration combines the 1 Write algorithmic function definition to find
de
external interface (its local state) with an the minimum among 3 numbers.
fid
fid
fid
implementation of that interface (the code Ans. let min 3 xy
z :=
if x < y then
on
on
on
on
thtancarries out the behaviour). An object
is instance created fromn the class. The ifx < z then x else z
C
C
an
interface defines object's visibility to the else
outside world. ify <z then y else z
:
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.
l
l
(ii) How the object is processed and executed is Ans. let rec sum num:
ia
tia
tia
tia
the implementation. if (num!=0) then return num+sum num-1)
nt
en
en
en
(iii) A class declaration combines the else
de
id
id
implementation of that interface (the code
PTA QUESTIONS AND ANSWERS
f
f
that carries out the behaviour).
on
on
on
on
For example, let's take the example of 1
MARK
increasing a car's speed.
C
C
1. A
function definition which call itself : (PTA-1]
ENGINE (a) Pure function (b) Impure function
(c) Normal function
(d) Recursive function
l
l
ia
ia
ia
ia
nti
[Ans. (d) Recursive function]
nt
3 MARKS
en
en
en
getSpeed
de
fid
fid
fid
on
on
on
Pull Fuel
speed Ans. let min x y z :=
3
Yes
ifx < z then x elsez
Son
Return else
ify <z then y else z
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
3. Identify Which of the following are Ans. (a) List
constructors and selectors?
(a) NI=number()
[PTA-5] (b) Tuple
(c) Class
Confide
(b) accetnum(nl)
l
l
(dy Tuple
ia
tia
tia
tia
(c) displaynum(nl)
(e) List
nt
en
en
en
(d) eval(a/b)
() Class
de
fid
fid
() display()
ANSWER THE FOLLOWING QUESTIONS
on
on
on
on
Ans. (a) Constructors
(b) Selectors (5 MARKs)
C
C
(c) Selectors
(d) Selectors
(e) Constructors
ntial 1. How will you facilitate data abstraction.
Explain it with suitable example. [PTA-2, 4]
() Selectors Ans. Data abstraction is supported by defining an
l
l
abstract data type (ADT), which is a collection
ia
tia
tia
tia
4. What are the different ways to access the of constructors and selectors. To facilitate data
nt
en
en
abstraction, you will need to create two types of
de
fid
fid
two ways. The first way is via our familiar Constructors :
on
on
on
(i)
unpacks a list into its elements and binds abstract data type.
each element to a different name.
C
C
Ist := [10, 20] (ii) Constructors create an object, bundling
together different pieces of information.
X, yi= lst For example, say you have an abstract data
(ii)
(i) In the above example x will becomel0 and type called city.
y will become 20.
l
l
(iv) This city object will hold the city's name,
ia
tia
tia
tia
(ii) A second method for accessing the and its latitude and longitude.
nt
en
en
en
elements in a list is by the element selection () To create a city object, you'd use a function
de
operator, also expressed using square like city = makecity (name, lat, lon).
id
id
id
brackets. Unlike a list literal, a square
(vi) Here makecity (name, lat, lon) is the
f
f
brackets expression directly following
on
on
on
on
another expression does not evaluate to a constructor which creates the object city.
list value, but instead selects an element ----- value passed as parameter
C
C
(name, lat, lon)
from the value of the preceding expression,
lst[0]
10 make city()
Ist[1]
l
l
ia
ia
ia
ia
20
Identify Which of the following are List, Tuple
nt
5. city
ent
en
en
en
and class ?
de
lat |lon
arr [1, 2, 34]
fid
fid
fid
(a)
(b) arr (1, 2, 34) Constructor
fia
on
on
on
on
(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.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(iii) To extract the information of a city object, Pair:
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
l
l
getlon(city) List can be called as Pairs.
ia
tia
tia
tia
These are the selectors because these
nt
functions extract the information of the 3. How will you access the multi-item? Explain
en
en
en
city object. with example.
de
fid
fid
fid
----> value passed as parameter city -----value passed as parameter
city city ----->value passedas parameter
Ans. (i) The structure construct (In O0OP languages
it's called class construct) is used to
on
on
on
on
getname()
getlat () getlon () represent multi-part objects where each
part is named (givena name). Consider the
C
C
following pseudo code:
2. What is a List? Why List can be called as Pairs. classs Person:
Explain with suitable example. [PTA-6]
Ans. List :
fiden
creation()
firstName:="" nfident
l
l
ia
tia
tia
tia
(i) List is constructed by placing expressions
lastNamne:=
within square brackets separated by
nt
en
en
en
commas. Such an expression is called a list id:=""
de
fid
fid
value can be of any type and can even be The new data type Person is pictorially
another list. represented as
on
on
on
on
Example for List is [10, 20].
Person class name (multi part data representation)
The elements of a list can be accessed in
C
C
(ii)
two ways. The first way is via our familiar
method of multiple assignment, which function belonging to the new datatype
creation (O|
unpacks a list into its elements and binds
each element to a different name.
l
l
Ist := [10, 20] first Name
ia
tia
tia
tia
X, y:= lst
nt
afide
en
en
en
(ii) In the above example x will becomel0 and datatype
de
id
id
accessing the elements in a list is by the email
f
f
element selection operator, also expressed
on
on
on
on
using square brackets. Let main() contains
C
C
(iv) Unlike a list literal, a square-brackets pl:=Person() statement creates
expression directly following anether the
object
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
l
l
ia
ia
ia
ia
en
en
lst[1] Baskar
de
fid
fid
20
id value 994-222
(v) In both the example mentioned above
on
on
on
on
1234
mathematically we can represent list similar
to a set. email="[email protected]"setting a filed called
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(i) 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
person. (c) Classes (d) Abstraction
(ii) Person is referred to as a class or a type, [Ans. (d) Abstraction]
l
l
while pl is referred to as an object or an
ia
tia
tia
tia
instance. 3. Which of the following is a type for objects
nt
en
en
en
(iv) Here class Person as a cookie cutter, and
a set of operations?
de
fid
fid
cutter you can make many cookies. Same (a) User-defined datatype
way using class created many objects of that (b) Derived datatype
on
on
on
on
type. (c) Built-in datatype (d) Abstract datatype
(v) A class defines a data abstraction by
C
C
[Ans. (d) Abstract datatype]
grouping related data items. A class is not
just data, it has functionsdefined within it. 4. ADT behavior is defined by
We say such functions are subordinate to (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
l
l
with the data of the class.
ia
tia
tia
tia
(a) i, ii (b) ii, iii
nt
en
en
de
fid
fid
5. The process of providing only the essentials
1. Expansion ADT:
of
and hiding the details is known as
on
on
on
on
[PTA-1]
(a) Abstract Data Tuple (a) Functions (b) Abstraction
C
C
(b) All Data Template (c) Encapsulation (d) Pairs
(c) Abstract Data Type |Ans. (b) Abstraction]
(d) Application Data Type
[Ans. (c) Abstract Data Type] 6. Whichofthe followinggives an implementation
independent view?
ADT can be implemented using.
l
l
2.
[PTA-5]
(b) Concrete
ia
tia
tia
tia
(a) Abstract
(a) singly linked list (b) doubly linked list (c) Datatype
nt
en
en
en
(c) either A or B (d) neither A nor B (d) Behavior of an object
de
id
id
How many ways to implement an ADT?
f
f
GovERNMENT EXAM QUESTIONS AND ANSWERS
on
on
on
on
(a) Only one (b) Two
1 MARK (c) Three (d) Many
C
C
1. Thedatatype whose representation is unknown |Ans. (d) Many]
is called [HY-2019]
8. Which of the following are implemented using
(a) Built-in datatype (b) Derived datatype & lists?
(c) Concrete datatyype (d) Abstract datatype
l
ia
ia
ia
en
en
fid
fid
on
on
on
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?
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
3. Define Enclosed scope with an example.
[PTA-3]
Ans. Output:
fident
Ans. (i) All programming languages permit
ide Red Blue Green
Red Blue
l
l
functions to be nested. A function (method)
ia
tia
tia
tia
Red
within another function is called nested Scope of Variables :
nt
en
en
en
function.
Variables
de
Scope
(ii) A variable which is declared inside a
fid
fid
fid
function which contains another function Color:=Red Global
definition with in it, the inner function
on
on
on
on
can also access the variable of the outer b:=Blue Enclosed
C
C
function. This scope is called enclosed G:=Green Local
scope.
PART - IV
(iii) When a compileror interpreter search for a
variable in a program, it first search Local, ANSWER THE FOLLOWING QUESTIONS
and then search Enclosing scopes. Consider
l
l
(5 MARKS)
ia
tia
tia
tia
the following example
nt
en
en
en
1. Disp): Entire program Output Explain the types of scopes for variable or
de
fid
fid
Disp()
3, Displ(): a:=10 Program Ans. Types of Variable Scope :
Disp 1( ):
print a 10 There are 4 types of Variable Scope, let's discuss
on
on
on
on
4. print a
5. Displ) Disp 1(): 10 them one by one:
print a
C
C
6. print a Local Scope :
Disp()
7. Disp() () Local scope refers to variables defined in
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
l
l
ia
tia
tia
tia
Ans. (i) Access control isa security technique that Outer scopes are checked.
regulates who or what can view or use
nt
en
en
resources in a computing environment.
de
id
id
minimizes risk to the object. 2. a:=7 of the
f
f
Disp( ): Program
on
on
on
on
(ii) In other words access control is a selective 3. print a a:=7
print a 7
restriction of access to data. 4. Disp()
C
C
(iv) In oops Access control is implemented Disp ()
lential
l
color:= Red
ia
ia
ia
ia
Global Scope:
en
en
en
b:=Blue
de
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
Entire program Entire program
C
1. a:=10 Output Library files
2. Disp(): of the Built in/module scope associated
a:=10
3.
4.
a:=7
print a
Disp(
a:=7
print a
)
Program
7 nfid Disp()
Disp 1( ):
with the software
Conf
l
l
5. Disp(), Disp 1(): 10 print a
ia
tia
tia
tia
6. print a print a Disp 1():
nt
print a
en
en
en
de
fid
fid
'a' which is defined inside the function
displays the value 7 for the function call LEGB rule:
on
on
on
on
Disp() and then it displays 10, because a is
defined in global scope. The LEGB rule is used to decide the order
C
C
in which the scopes are to be searched
Enclosed Scope :
for scope resolution. The scopes are listed
() All programming languages permit below in terms of hierarchy (highest to
functions to be nested. A function (method) lowest).
l
l
with in another function is called nested
nfic
ia
tia
tia
tia
Local(L) Defined inside function/
function.
nt
class
en
en
en
(i) A variable which is declared inside a Enclosed(E) Defined inside enclosing
de
fid
fid
functions (Nested
definition with in it, the inner function
can also access the variable of the outer function concept)
on
on
on
on
function. This scope is called enclosed Global(G) Defined at the uppermost
C
C
scope. level
(ii) When a compiler or interpreter search for a Built-in (B) Reserved names in built
variable in a program, it first search Local, in functions (modules)
and then search Enclosing scopes. Consider
l
l
BUILT-IN
the following example
ia
tia
tia
tia
onfider
nt
Entire program
nfide
1. Disp(): Output GLOBAL
en
en
en
de
id
Disp()
id
3. Disp10: a:=10 Program LOCAL
f
f
Disp 1():
on
on
on
on
a
4. printa print 10
Disp 1():
5. Disp10 10
C
C
print a
6. print a Disp()
7. Disp()
2.
Write any Five Characteristics of Modules.
[PTA-4,6; HY-2019]
(iv) In the above example Disp1() is defined
Ans.The following are the desirable characteristics of
l
ia
ia
ia
a module.
Disp() can be even used by Displ) because
nt
en
en
fid
fid
()) The built-in scope has all the names that are
(ii) Modules can be separately compiled and
stored in a library.
on
on
on
on
(ii) Any variable or module which is defined (iv) Module segments can be used by invoking
in the library functions of a programming a nameand some parameters.
language has Built-in or module scope. (v) Module segments can be used by other
Consider the following example. modules.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
3
Chapter
3. Write any five benefits in using modular
programming. [Govt. MQP-2019]
idert sum20
numl:= numl + 10
Confident
Ans. (i) Less code to be written. sum2()
l
l
ia
tia
tia
tia
(ii) A single procedure can be developed for sum1()
nt
en
en
en
- code many times. sum()
de
fid
fid
1
Unit
because a small team deals with only a
on
on
on
on
small part of the entire code. PTA QUESTIONS AND ANSWERS
(iv) Modular programming allows many
C
C
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-I)
(vi) Code is short, simple and easy to
l
l
(a) Local (b) Global
ia
tia
tia
tia
understand. (c) Enclosed (d) Built-in
nt
en
en
JAns. (c) Enclosed]
localized to a subroutine or function. Which are loaded as soon as the library files
de
fid
fid
fid
(vii) The same code can be used in many are imported to the program? [PTA-3]
applications. (a) Built-in scope variables
on
on
on
on
(ix) The scoping of variables can easily be (b) Enclosed scope variables
(c) Global scope variables
C
C
controlled.
(d) Local scope variables
HANDS ON PRACTICE |Ans. (a) Built-in scope variables]
1. Observe the following diagram and Write the 3. Which of the following is not the example of
modules? [PTA-5]
l
l
pseudo code for the following.
ia
tia
tia
tia
(a) procedures (b) subroutines
nt
en
en
(d) functions
de
id
id
numl:=20
2 MARKS
f
f
on
on
on
on
sum1()
numl:=numl + 10 1. What are modules? [PTA-4]
C
C
Ans. A module is a part of a program. Programs
sum2() are composed of one or more independently
numl: = numl + 10
developed modules.
sum2()
GoVERNMENT EXAM QUESTIONS AND ANSWERS
l
denNa
ia
ia
ia
ia
sum1()
1 MARK
nt
t
en
en
en
numl:=10 1.
fid
fid
fid
on
on
on
Ans. sum():
Cor (c) print a (d) Disp()
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
PART - IV Pseudo code:
ANSWER THE FOLLOWING QUESTIONS () Traverse the array using for loop
MARKS)
(i) In every iteration, compare the target
(5 search key value with the current value of
l
l
ia
tia
tia
tia
1. Explain the characteristics of an algorithm. the list.
nt
en
en
en
Ans. [PTA-5; HY-2019]
current index and value of the array
de
fid
fid
If the values do not match, move on
supplied. to the next array element.
on
on
on
on
Output At least one quantity is produced. (ii) If no match is found, display the search
element not found.
C
C
Finiteness Algorithms must terminate after
finite number of steps. Example
Definiteness All operations should be well
To search the number 25 in the array given
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
l
l
in the given array if the search element is found
ia
tia
tia
tia
taking square root for negative
number are unacceptable. that index is returned otherwise the search is
nt
en
en
en
Effectiveness Every instruction must be carried Continued till the last index of the array. In this
de
fid
fid
Correctness The algorithms should be error index 1
23 4
on
on
on
on
free. values 10 12 20 25 30
Simplicity East to implement.
C
C
Example 1:
Unambiguous Algorithm should be clear and Input: values[]= {5, 34, 65, 12, 77, 35}
unambiguous. Each of its steps target = 77
and their inputs/outputs should Output: 4
be clear and must lead to only one Example 2:
l
l
ia
tia
tia
tia
meaning. Input: values] = {101, 392, 1, 54, 32, 22, 90, 93}
nt
en
available resources.
en
de
id
id
Portable An algorithm should be generic,
independent of any programming 3. What is Binary search? Discuss with example.
f
f
on
on
on
on
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
C
C
Independent An algorithm should have of a search element within a sorted array. The
binary search algorithm can be done as divide
step-by-step directions, which
should be independent of any and-conquer search algorithm and executes in
logarithmic time.
programming code.
Pseudo code for Binary search :
l
l
ia
ia
ia
ia
2. Discuss about Linear search algorithm. Start with the middle element:
nt
en
en
fid
fid
on
on
on
element is found or the list is exhausted. In (ii) If the search element is greater than the
number in the middle index, then select
ths searching algorithm, list need not be the elements to the right side of the middle
ordered.
index, and go to Step-1.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(iv) If the search element is less than the (viii) The value stored at location or index 7 is
number in the middle index, then select not a match with search element, ratherit is
the elements to the left side of the middle
index, and start with Step-1. ide more than what we are looking for. So, the
search element must be in the lower part
l
l
(v) When a match is found, display success
ia
tia
tia
tia
message with the index of the element from the current mid value location
nt
matched.
en
en
en
(vi)If no match is found for all comparisons, |10||20|30|40||5060 70||80||90|99
de
fid
fid
Binary Search Working principles : not found. Hence,
(ix) The search element still
on
on
on
on
(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.
C
C
example describes the step by step operation
of binary search. O high = mid -1
mid = low + (high- low)/2
(ii) Consider the following array of elements,
the array is being sorted so it enables to do fident Now the mid value is 5.
l
l
the binary search algorithm. Let us assume
ia
tia
tia
tia
that the search element is 60 and we need
nt
en
en
de
fid
fid
1020|30|4050||60||7o80|9099 (x) Now we compare the value stored at
location 5 with our search element. We
on
on
on
on
1 2 4
found that it is a match.
First, we find index of middle element of
C
C
(iii)
the array by using this formula : 10|20||30|40||5060||70||80|9099
mid = low + (high - low) / 2 0 2 3 4 5 6 7 8
(iv) Here it is, 0 + (9 -0)/2= 4 (fractional part
ignored). So, 4 is the mid value of the array.
l
l
(xi) We can conclude that the search element 60
ia
tia
tia
tia
is found at location or index 5.For example
nt
fide
en
en
en
if we take the search element as 95, For this
de
id
id
12 3 4 5 6 7 8
(v) Now compare the search element with the
f
f
unsuccessful result.
on
on
on
on
value stored at mid value location 4. The
value stored at location or index 4 is 50, 4. Explain the Bubble sort algorithm with
C
C
which is not match with search element. As example. [PTA-6]
the search value 60is greater than 50. Ans. Bubble sort algorithm:
10||20|30 5060|708090|99 () Bubble sort is a simple sorting algorithm.
3 7
The algorithm starts at the beginning of the
1
4 5 6 8
list of values stored in an array. It compares
l
l
ia
ia
ia
ia
(vi) Now we change our low to mid + and find 1 each pair of adjacent elements and swaps
nt
en
en
fid
fid
on
on
on
(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
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(iv) Assume list is an array of n elements. The (ii) Dynamie programming is used whenever
swap function swaps the values of the given
problems can be divided into similar
array elements.
sub-problems. So that their results carn be
Pseudo code re-used to complete the process.
()) Start with the first element i.e., index = 0,
l
l
(iv) Dynamic programming approaches are
ia
tia
tia
tia
compare the current element with the next used to find the solution in optimized way.
nt
en
en
en
For every inner sub problem, dynanmic
de
(iü) If the current element is greater than the algorithm willtryto check the results of the
fid
fid
fid
next element of the array, swap them. previously solved sub-problems.
(v) The solutions of overlapped sub-problems
on
on
on
on
(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
solution.
C
C
next element. Go to Step 1 and repeat until
end of the index is reached. Steps to do Dynamic programming :
(iv) Let's consider an array with values {15, 11, () The given problem will be divided into
16, 12, 14, 13} Below, we have a pictorial smaller overlapping sub-problems.
representation of how bubble sort will sort
l
l
(i) Anoptimum solution for the given problem
ia
tia
tia
tia
the given array. can be achieved by using result of smaller
nt
en
en
en
15>11
So interchange 15 11 16 12 14 13
sub-problem.
de
fid
fid
Fibonacci Series - Anexample :
15>16 15 11 16 12 14 13
No swapping
on
on
on
on
() Fibonacci series generates the subsequent
C
C
16>12 11 15 16 12 14 13 number by adding two previous numbers.
So interchange
Fibonacciseries starts from two numbers
Fib 0 & Fib 1. The initial values of Fib0&
16>14 11
Fib lcan be taken as 0 and 1.
So interchange 15 12 16 14 13
(ii) Fibonacci series satisfies the following
l
l
ia
tia
tia
tia
16>13
conditions :
11 13
Fibn = Fib.,+ Fib,,
16
151214
nt
So interchange
en
en
en
n-2
(ii) Hence, a Fibonacci series for the n value 8
de
id
id
=
Fib, 0
112358 13
f
f
(v) The above example is for
pictorial
on
on
on
on
iteration-1. Similarly, remaining iteration Fibonacci Iterative Algorithm with Dynamic
can be done. The final iteration will give the programming approach The following
C
C
a
example shows simple Dynamic programming
sorted array. At the end of all the iterations
we will get the sorted values in an array as approach for the generation of Fibonacci series.
:
given below Initialize f0=0, fl =1
11 12 13 14 15 16
step-1:Print the initial values of Fibonacci f0
l
and fl
ia
ia
ia
ia
t
en
en
en
fid
fid
on
on
on
(i) 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
is divided into smaller and yet smaller
series as shown below:
The Fibonacci series is : 0 112358 13 21 34 55.
possible sub-problems.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
5. What are string literals? Explain. le "Untitled
Eile Edit Fgrmat Bun Options Window Help
Confide
Ctrl+N
Open.. Ctrl+0
characters surrounded by quotes. Python Open Modul.
Recent Files
AitM
l
ia
tia
tia
tia
Path Browser
for a string. ave Ctil-S
nt
en
en
en
(ii) Save Copy As.. Alt Shift+S
de
fid
fid
m Close Alt+F4
value with triple-quote " is used to
give Exit Ctrl+Q
on
on
on
To test String Literals :
Ln:4 Co: 21
C
C
# Demo Program to test String Literals To Save the file First time
l
ia
tia
tia
tia
with more than one line code." ie Sve As
New Volume
Cemputer (D) Dyhond.?
nt
print (strings)
en
en
en
Grgarite ew foiäer
de
fid
fid
30 Recet Plsces
print (multiline_str) Downioats
on
on
on
on
# End of the Program Librti
Decuments
Output: Musk
C
C
Pictures
Computa
one line code. Mide Folders File Name (demol) Save Cancel
l
l
ia
tia
tia
tia
File Type (Python file (py)
PART IV
nt
en
en
en
Save As Dialog Box
ANSWER THE FOLLOWING QUESTIONS
de
id
id
(5 MARKs) location where you want to save your
f
f
on
on
on
on
Python code, and type the file name in File
1. Describe in detail the procedure Script mode Name box. Python files are by default saved
C
C
programming. with extension -py. Thus, while creating
Ans. A script is a text file containing the Python Python scripts using Python Script editor,
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
l
ia
ia
ia
t
en
en
en
fid
fid
Confi
Python Shel
(ii) An untitled blank script text editor willbe
on
on
on
on
a=100
Check Module Alt+X
b=350 Run Module
displayed on screen. c=atb
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(ii) If code has any error, it will be shown in (vii) The input ( ) accepts all data as string
red color in the IDLE window, and Python or characters but not as numbers. If a
describes the type of error occurred. To
correct the errors, go back to Script editor,
de numerical value is entered, the input values
should be explicitly converted into numeric
l
l
ia
tia
tia
tia
make corrections, save the file using Ctrl + S data type. The int( ) function is used to
or File Save and execute it again.
nt
en
en
en
(iii) (For all error free code, the output will
de
fid
fid
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: "))
on
on
on
on
Ans. Input and Output Functions : A program print ("Thesum =x+y)
needs to interact with the user to accomplish the
C
C
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
function print() is used to display the result of
the program on the screen after execution.
Enter Number 2: 56
The sum= 90
enti
l
l
ia
tia
tia
tia
The input() function: The print) function :
nt
en
en
(i)
accept data as input at run time. The syntax display result on the screen, The syntax for
de
fid
fid
fid
for input() function is, print() is as follows:
Variable = input ("prompt string")
(i) Example :
on
on
on
on
(ii) Where, prompt string in the syntax is a
statement or message to the user, to know print ("string to be displayed as output ")
C
C
what input can be given. print (variable )
(i) Ifaprompt string is used, it is displayed on print ("String to be displayed as output ;
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
l
l
variable, "String 3" ....)
ia
tia
tia
tia
and stores the entered data in the given
variable. (ii) Example :
nt
en
en
en
(iv) If prompt string is not given in input( ) no print ("Welcome to Python
de
id
id
the user will not know what is to be typed Welcome to Python Programming
f
f
as input.
Cor
on
on
on
on
Example 1 : input()with prompt string >>>x=5
() >>> y=6
>>> city=input ("Enter Your City:")
C
C
Enter Your City: Madurai >>>Z= X+ y
>>> print ("I am from", city) >>> print (z)
Iam from Madurai 11
:
(vi) Example 2 input() without prompt string >>> print ("The sum =z)
l
>>> city=input()
ia
ia
ia
ia
The sum = 11
Madurai
nt
en
en
fid
fid
(vii) Note that in example-2, the input( ) is not The sum of and 6 is 11
5
having any prompt string, thus the user will The print () evaluates the expression before
on
on
on
on
(v)
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
more than one item.
with input( ).
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
3. Discuss in detail about Tokens in Python. Output:
The sum = 110
[PTA-3; QY-2019]
Ans. Python breaks each logical line into a sequence nfide The a>b= True fide
l
l
a>
of elementary lexical components known as
a
The bor ==b=True
ia
tia
tia
tia
Tokens. The normal token types are The a+=10is = 110
nt
(i) Identifiers,
en
en
en
(iv) Delimiters : Python uses the symbols
(i) Keywords,
de
fid
fid
(iv) Delimiters and expressions, lists, dictionaries and strings.
(v) Literals. Following are the delimiters.
on
on
on
on
(i) Identifiers : (
An Identifier is a name used to identify a
C
C
variable, function, class, module or object.
An identifier must start with an alphabet += %=
(A.Z or a..z) or underscore (_). &= <<= **
Identifiers may contain digits (0..9).
Python identifiers are case sensitive i.e. (v) Literals :
Literal is a raw data given in a
l
l
ia
tia
tia
tia
uppercase and lowercase letters are distinct. variable or constant. In Python, there are
Identifiers mut not be a python keyword.
en
en
en
Python does not allow punctuation Numeric Literals consists of
de
fid
fid
identifiers.
String literal is a sequence of
Example : characters surrounded by quotes.
on
on
on
on
Example of valid identifiers : Sum, total
marks, regno, num l
Boolean literal can have any of the
C
C
two values : True or False.
Example of invalid identifiers : 12Nanme,
name$, total-mark, continue PTA> QUESTIONS AND ANSWERS
(ii) Keywords :
Keywords are special words used by Python
interpreter to recognize the structure of MARK
l
l
program..
ia
tia
tia
tia
As these words have specific meaning for 1. What will be the value of X from the following
nt
en
en
de
other purpose. A,
B=10, 3
Python keywards : false, class, If, elif, else,
id
id
id
pass, break etc.
X=A if (A/B==3) else B
f
f
print(X)
on
on
on
on
(ii) Operators : (b) 10
. In computer programming languages (a) 3
C
C
operators are special symbols which (c) True (d) False
represent computations, conditional [Ans. (d) False]
matching etc.
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,
l
tial
ia
ia
ia
ia
en
en
Example :
fid
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
PART- IV
ANSWER THE FOLLOWING QUESTIONS idén nfider
for each item
in sequence
l
l
(5 MARKs)
ia
tia
tia
tia
nt
en
en
en
1. Write a detail note on for loop. Yes
de
fid
fid
reached?
Ans. (i) for loop : for loop is the most comfortable
on
on
on
on
loop. It is also an entry check loop. The
condition is checked in the beginning and
C
C
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
(i) Syntax:
l
l
for counter_variable in sequence:
ia
tia
tia
tia
statements-block i Exit loop
nt
en
en
en
[else # optional block
for loop execution
de
statements-block 2]
fid
fid
fid
Example :
(ii) (The counter_variable mentioned in the
#Program to illustrate the use of for loop - to
on
on
on
on
syntax is similar to the control variable
that we used in the for loop of C++ and print single digit even number
C
C
the sequence refers to the initial, final for iinrange (2,10,2):
and increment value. Usually in Python, print (i, end=')
for loop uses the range() function in the Output :
sequence to specify the initial, final and 2
l
ia
tia
tia
tia
values starting from start till stop-1. 2. Write a detail note on if..else..elif statement
nt
en
en
:
Ans. Nested if..elif..else statement
de
id
id
Where, (i) When we need to construct a chain of if
f
f
start- refers to the initial value statement(s) then 'elif clause can be used
on
on
on
on
stop- refers to the final value instead of 'else'.
step - refers to increment value, this is
C
C
(ii) Syntax :
optional part. if<condition-1>:
Examples for range): statements-block1
range (1,30,1) - will start the range of values
elif <condition-2>:
from 1 and end at 29
l
statements-block 2
ia
ia
ia
ia
t
en
en
en
fid
fid
on
on
on
and starts the range count statements-block2 is executed and even ifit
from 0 to 19 (remember fails statements-block n mentioned in else
always range() will work till part is executed.
stop -1 value only)
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
n
C
C
Output 2
false
Enter mark in second subject: 73
Grade :B dey
3 Write a program to display all 3 digit odd
l
l
ia
tia
tia
tia
Test
numbers.
Con
nt
Expression false
Ans. fora in range (100, 1000):
en
en
en
of elif
de
True if a %2=-1:
fid
fid
fid
print b
on
on
on
on
Body of else :
Body of elif Output
.... 997, 999
C
C
101, 103, 105, 107
if.elif.else statement execution
4. Write a program to display multiplication
(iv)'elif clause combines if..else-if..else table for a given number.
statements to one if..elif...else. 'elif can Ans. Multiplication table : Rder
l
l
ia
tia
tia
tia
be considered to be abbreviation of 'else if'. num = int(input("Enter the number :
nt
en
en
clause that can be used, but an 'else' clause prit("multiplication Table of", num)
de
fid
fid
fid
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)
on
on
on
on
nested if statement Output :
C
C
Average Grade Enter the number:6
Multiplication Table of 6
>=80 and above A
6x1=6
=70 and <80
6x2= 12
>=60 and <70
l
l
ia
tia
tia
tia
6x3 18
>-50 and <60 D
Confider
nt
6×4=24
en
en
en
Otherwise E 6x5=30
de
id
id
6x6= 36
m2=int (input("Enter mark in second subject: ")
f
f
6x7=42
on
on
on
on
avg= (ml+m2)/2 8 =
48
6x
if avg>=80:
C
C
:
6x9= 54
print ("Grade A") 6x 10 60
=
ia
ia
ia
[QY-2019)
en
en
en
: Ans. Program :
print ("Grade D")
fid
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
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
external code. nfide function.
onfid
l
l
ia
tia
tia
tia
(ii) If the base condition is met then the X=20
program gives meaningful output and exits. y=-23.2
nt
en
en
en
(ii) Otherwise, function does some required print('x =, abs(x))
de
fid
fid
recursion. Output:
X= 20
What are the points to be noted while defining
on
on
on
on
8.
a function? [Govt. MQQP-2019) y= 23.2
C
C
(iii) Lambda Functions :
Ans. When defining functions there are multiple
In Python, anonymous function is a
things that need to be noted;
function that is defined without a name.
(i) Function blocks begin with the keyword While normal functions are defined using
"def" followed by function name and the def keyword, in Python anonymous
parenthesis ().
l
l
functions are defined using the lambda
ia
tia
tia
tia
(i) Any input parameters or arguments should keyword.
nt
en
en
you define afunction. Hence, anonymous functions are also
de
fid
fid
Example :
and is indented. sum = lambda argl, arg2: argl + arg2
on
on
on
on
(iv) The statement "return lexpression]"
exits a function, optionally passing back an print (The Sum is", sum(30,40)
C
C
expression tothe caller. A "return" with no pint (The Sum is :, sum(-30,40))
arguments is the same as return None. Output :
PART - IV
:
The Sum is 70
:
The Sum is 10
ANSWER THE FOLLOWING QUESTIONS (iv) Recursive function : Functions that calls
l
l
ia
tia
tia
tia
(5 MARKs) itself is known as recursive.
nt
en
en
:
works
de
id
id
Ans. Functions are named blocks of code that are
designed to do one specific job. external code.
f
f
on
on
on
on
(iü) If the base condition is met then the
Types of Functions :
(i) User Defined Function
program gives meaningful output and exits.
C
C
(iü) Built-in Function (iii) Otherwise, function does some required
(ii) Lambda Function processing and then calls itself to continue
(iv) Recursion Function recursion.
() User Defined Function: Example:
l
ia
ia
ia
t
en
en
en
fid
fid
on
on
on
Output:
def area(w,h): 1
return w*h
print (area (3,5)) 120
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
2. Explain the scope of variables with an example. Example : Accessing global Variable From
[PTA-3; HY-2019)
Ans.Scope of variable refers to the part of the fider Inside a Function
c=1
Confide
# global variable
program, where it is accessible, i.e., area where def add():
l
l
ia
tia
tia
tia
the variables refer (use). The scope holds the print(c)
nt
add()
en
en
en
current set of variables and their values. The two
Output:
de
fid
fid
1
on
on
on
function's body or in the local scope is known as
(a) id() (b) chr()
local variable.
C
C
(c) round() (d) type()
Rules of local variable :
(i) A variable with local scope can be accessed
only within the function/block that it is
created in.
Ans.
(a)
nti
(e) pow
[PTA-4, 6; QY-2019]
l
l
ia
tia
tia
tia
(ii) When a variable is created inside the Function Description Syntax Example
nt
en
en
en
function/block, the variable becomes local id () id() Return id x15
de
fid
fid
(iiii) A local variable only exists while the of an object. print ('address
on
on
on
on
function is executing. i.e. the
of x is :,id (x)
(iv) The formal arguments are also local to address of
C
C
the object in print ('address
function.
memory. of y is :id (y))
(v) Example: Create a Local Variable
Note: Output:
def loc():
The address address of x
l
l
ia
tia
tia
tia
y-0 # local scope
of x and y is :
dep
nt
en
en
1357486752
de
id
id
Output: is :
f
f
on
on
on
on
13480736
Global Scope variable, with global scope
: A
(b)
C
C
[PTA-4)
can be used anywhere in the program. It can be
Function Description Syntax Example
created by defining a variable outside the scope
of any function/block. chr () Returns the chr (i) c=65
Unicode d=43
Rules of global Keyword :
l
l
ia
ia
ia
ia
en
en
ASCII value.
function, it's global by default. You don't
dep CXfice
Output:
fid
fid
fid
This function
have to use global keyword.
on
on
on
on
is inverse
(ii) We use global keyword to read and write a
of ord()
global variable inside a function.
C
function.
(iii) Use of global keyword outside a function
has no effect.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(c) 4. Write a Python code tofind the L.C.M.of two
Function Description Syntax Example numbers.
Ans. Program :
round ()Returns round def lcm(x, y):
l
l
ia
tia
tia
tia
the nearest (number ifx>y:
integerto itsndigits])2=-18.3
nt
en
en
en
greater =X
input.
de
else:
1. First
fid
fid
fid
greater =y
argument while (True):
on
on
on
on
(number) if ((greater % x == 0) and (greater % y ==
is used to
0)):
C
C
specify the
Kofidghtial,
value to be
lcm = greater
break
rounded.
t1
greater
return lcm
a = int (input ("Enter first number :") er
l
l
ia
tia
tia
tia
b= int (input ("Enter second number :"))
nt
en
en
to', round
de
fid
fid
[PTA-5]
(d) [PTA-4; QY-2019)
Ans. (i) A Functions that calls itself is known as
on
on
on
on
Function Description Syntax Example recursive.
When a function calls itself is known as
C
C
type () Returns the type X= 15.2 (ii)
type of object (object) y='a' recursion.
for the given S= True (ii) Recursion works like loop but sometimes
|singleobject. print (type it makes more sense to use recursion than
Note:
tia (x)) loop.
l
l
print (type Imagine a process would iterate indefinitely
ia
tia
tia
tia
This function (iv)
(y)
used with if not stopped by some condition is known
nt
en
en
en
|single object print (type as infinite iteration.
de
id
id
oni Output: function is known as base condition.
f
f
<class 'float'> (vi) A base condition is must in every recursive
on
on
on
on
<class 'str> function otherwise it will continue to
<class 'bool'> execute like an infinite loop.
C
C
(e) (vii) Python stops calling recursive function
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).
l
ntia)
ia
ia
ia
ia
t
en
en
en
fid
fid
on
on
on
recursion.
Here is an example of recursive function
used to calculate factorial.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
Example : 3. Evaluate the following functions and write the
def fact(n): output:
ifn=0:
Cofig SI.No. function Output
l
l
ia
tia
tia
tia
return 1 1
1. abs (-25+12.0)
nt
en
en
en
Co return n * fact (n-1)
de
2, 1. ord(2)
fid
fid
fid
print (fact (0) 2. ord($')
print (fact (5)) 3. type('s)
on
on
on
on
Output: 4. bin(16)
C
C
1
5. 1,chr(13)
HANDS ON PRACTICE
1. Try the following code in the above program.
6.
|2.print(chr(13))
1.round(18.2,1)
2. round(18.2,0)
enle
l
l
ia
tia
tia
tia
Code 3. round(0.5100,3)
SI.No. Result
4. round(0.5120,3)
nt
H- printinfo("3500")
en
en
en
1.
7. 1. format(66, 'c')
de
2. printinfo("3500","Sri")
fid
fid
fid
2. format(10, 'x)
3. printinfo(name="balu") 3. format(10, X)
on
on
on
on
4. printinfo("Jose", 1234) 4. format(0b1 10, 'd)
5. format(Oxa, 'd')
5. printinfo(""salary=1234)
C
C
Ans.Output : 8. 1. pow(2,-3)
1.
2.
Error
Name: Sri
Salary: 3500 eans 2. pow(2,3.0)
3. pow(2,0)
4. pow(1+2),2)
l
l
ia
tia
tia
tia
3. Name: Balu |5. pow(-3,2)
nt
Salary:3500
6. pow(2*2,2)
Confida
en
en
Ans. Output
en
:
de
4. Name: Jose
id
id
id
1. 13
Salary: 1234
2. 3.2
f
f
Name:
on
on
on
on
5. 2. 1. 50
Salary: 1234 2. 36
C
C
3. <class 'str'>
2. Evaluate the following functions and write the 4. Ob10000
output. 5. 1. CR (carriage return)
SI.No. Function Output 2. It moves the cursor to the beginning of
same line
1. eval('25*2-5*4')
l
6. 1. 18.2
Confidentia
ia
ia
ia
ia
2. math.sqrt(abs(-81)
nt
t
en
en
en
3. math.ceil(3.5+4.6)
Cofider
de
4. math.floor(3.5+4.6)
fid
fid
fid
hfi
:
Ans. Output
on
on
on
on
1. 30
C
2.
3. 8.
4.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
3. What willbe the output of the given python PART- IV
program?
ANSWER THE FOLLOWING QUESTIONS
strl ="welcome"
l
l
(5 MARKs)
ia
tia
tia
tia
str2 ="to school"
str3 = strl[:2]+str2[len(str2)-2:] Explain about string operators in python with
nt
en
en
en
print(str3) suitable example. PTA-2; HY-2019)
de
fid
fid
following operators for string operations. These
4. What is the use of format( )? Give an example. operators are useful to manipulate string.
on
on
on
on
[HY-2019] (i) Concatenation (+): Joining oftwo or more
Ans. (i) )
The format( function used with strings is strings is called as Concatenation. The plus
C
C
very versatile and powerful function used (+) operator is used to concatenate strings
for formatting strings in python.
(i) The curly braces (} are used as placeholders
or replacement fields which get replaced
along with format() function.
Example :
S>"welcome" + "Python"
ntia
welcomePython'
l
l
ia
tia
tia
tia
(ii) Example : (iy Append (t ): Adding more strings at
num]=int (input("Number 1: ")
id the end of an existing string is known as
nt
en
en
en
num2-int (input("Number 2: ")) append. The operator += is used to append
de
print ("The sum of and is O". a new string with an existing string.
fid
fid
fid
format(numl,num2,(numl +num2))) Example :
>>> strl="Welcome to
on
on
on
on
Output:
>>> strl+="Learn Python"
Number l: 34
>>> print (str1)
C
C
Number 2: 54
The sum of 34 and 54 is 88 Welcome to Learn Python
Write a note about count() function in python. (i) Repeating (") :The multiplication operator
5. () is used to display a string in multiple
Ans. number of times.
entia
l
l
Example :
ia
tia
tia
tia
Syntax Description Example
>>> strl="Raja Raja
>> strl="Welcome
nt
en
en
(str, beg, number of Chozhan'"
de
id
id
(iv) String slicing :
occurs count('Raja')) Slice is a substring of a main string.
f
f
on
on
on
on
within the 2 A substring can be taken from the original
given range. >>> print(strl, string by using | |slicing operator and
C
C
Remember count(r)) index values.
that substring Using slice operator, you have to slice one
or more substrings from a main string.
may be a
single>>> print(strl. General format of slice operation :
character. count(R')
str[start:end]
l
Range (beg
ia
ia
ia
ia
t
en
en
en
are optional. Python takes the end value less than one
5
fide
fid
fid
fid
on
on
on
count('a,0,5))
slice a single character from a string
searched in 2
>>>strl="THIRUKKURAL"
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(v) Stride when slicing string: wrapped-textwrap.fill(text_without_
When the licing operation, you can specify
a third argument as the stride, which refers
to the, number of characters to move
print(textwrap.indent(wrapped, "*)
print ()
nfide
Indentation, width=50),
l
l
forward after the first character is retrieved Output :
ia
tia
tia
tia
from the string. Strings are immutable. Slice is a
nt
en
en
en
The default value of stride is 1. * substring of a main string. Stride
de
Python takes the last value as n-1. *is a third argument in slicing operation
fid
fid
fid
You can also use negative value as stride, to 4. Write a program to print integers with * on
prints data in reverse order. the right of specified width.
on
on
on
on
x
Example : Ans. =123
C
C
>>>strl="Welcome to learn Python" print("original number:", x)
>>>print (str1[10:16|) print('formatted number(right padding, width
>>>print (strl[::-21) 6):"+" *<7d}".format(x);
Output : Output
original number: 1 23
l
l
Learn
ia
tia
tia
tia
nhy re teolW formatted number(right padding, width 6):
123***
nt
en
en
en
5. Write a program to create a mirror of the given
de
HANDS ON EXPERIENCE
string. For example, "wel" = "lew".
fid
fid
fid
a
1. Write a python program to find the length of Ans. strl= input ("Enter string")
a string. = «
on
on
on
on
str2
Ans. str = input ("Enter a string") index = -1
C
C
print (len(str)) for iin strl:
Output : str2 = strl[index]
Enter a string HELLO
:
index - =1
5 print ("The given string =(}\n The Reversed string
={}'format(strl, str2))
Write a program to count the occurrences of
l
l
2.
ia
tia
tia
tia
each word in a given string. Output :
nt
en
en
Ans. def word_conunt(str):
The given string = welcome
de
de
counts=dict()
The Reversed string = emoclew
id
id
id
words=str.split()
for word in words: 6. Write a program to removes all the occurrences
f
f
on
on
on
on
if word in counts: of a give character in a string.
counts[word]+=1 Ans. def removechar(s,c):
C
C
else: # find total no of occurrence of a character
counts[word]=1 counts = S.count(c)
return counts # convert into list of characters
print(word_count('the quick brown fox jumps
over the lazy dog.')) s= list(s)
l
ia
ia
ia
Output :
{'th':2, jumps' :
1, "brown: 1, :
lazy' 1, fox': while counts :
nt
t
en
en
en
fid
fid
a
lines in string. Counts –=1
#join remaining characters
on
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
:
(ii) Difference It includes all elelments that Example:
are in first set (say set A) but not in the
second set (say set B).
(iv) Symmetric difference : It includes all the
fide >> MyList=[34,98,47, Kannan',
'Gowrisankar', Lenin', 'Sreenivasan' ]
>>> MyList. insert(3, 'Ramakrishnan)
elements that are in two sets (say sets A and
l
l
>>> print(MyList)
ia
tia
tia
tia
B) but not the one that are common to two
Output: [34, 98, 47, 'Ramakrishnan', 'Kannan'
nt
sets.
en
en
en
'Gowrisankar, Lenin', 'Sreenivasan']
de
6. What are the difference between List and i) In the above example, insert( ) function
fid
fid
fid
Dictionary? [PTA-3; HY-2019)
inserts a new element 'Ramakrishnan' at
on
on
on
on
Ans. the index value 3, ie. at the 4th position.
List Dictionary (ii) While insertinga new element, the existing
C
C
(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():
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.
l
l
elements of any
ia
tia
tia
tia
element. (i) But, it includes elements at the end of a list.
nt
type. Syntax :
en
en
en
(ii) It is enclosed The key value pairs are, List.append (element to be added)
de
within square
fid
fid
fid
enclosed with curly Example :
brackets ) braces {} >>> Mylist=[34, 45, 48]
on
on
on
on
(ii) Syntax : Syntax or defining a >>> Mylist.append(90)
:
Variable= dictionary
C
C
>>>print(Mylist)
[element-1, Dictionary_Name
= {Key_1: Value_1, Output : (34, 45, 48, 90]
element-2,
element-3 ....... Key_2:Value_2, Adding more elements in a list using extend ):
element-n] ()) The extend( ) function is used to add more
l
l
than one element to an existing list.
ia
tia
tia
tia
Key_n: Value_n
(ii) In extend( ) function, multiple elements
nt
en
en
en
(iv) The commnas The keys in a Python should be specified within square bracket
de
id
id
separator for by a colon (:) while Syntax : List.extend ( [elements to be added])
f
f
on
on
on
on
:
the elements. the commas work as a Example
separator for the ele >>> Mylist=[34, 45, 48]
C
C
ments. >>> Mylist.extend([71, 32, 29])
PART - IV >>> print(Mylist)
:
Output (34, 45, 48, 90, 71, 32, 29]
ANSWER THE FOLLOWING QUESTIONS
2. What is the purpose of range( )? Explain with
l
l
ia
ia
ia
ia
What the different ways to insert an element in Ans. The range() is a function used to generate a series
en
en
en
1.
of values in Python. Using range() function, you
de
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
end value - upper limit of series. Python 3. What is nested tuple? Explain with an example,
C
(ii)
takes the ending value as upper limit - 1. Ans. Nested Tuples :
(ii) step value- t is an optional argument,
() In Python, a tuple can be defined inside
which is used to generate different interval
of values. nfi another tuple; called Nested tuple. In a
nested tuple, each tuple is considered as
l
l
ia
tia
tia
tia
Example: Generating whole numbers upto 10 an element. The for loop will be useful to
nt
en
en
en
access all the elements in a nested tuple.
de
print(x)
(i) Example :
fid
fid
fid
Output:
1
Toppers = ("Vinodini", "XII-F", 98.7),
on
on
on
on
2
("Soundarya", "XII-H", 97.5),
("Tharani", "XII-F", 95.3), ("Saisri",
C
C
3
4 nfidential for i in Toppers:
"XII-G", 93.8))
5
print(i)
6
(iüi) Output : Confide
l
l
7
ia
tia
tia
tia
Snfio (Vinodini, XII-F, 98.7)
nt
en
en
en
(Soundarya', XII-H, 97.5)
de
fid
fid
Creating a list with series of values :
('Saisri, "XII-G, 93.8)
on
on
on
on
) Using the range( ) function, a list can be 4. Explain the different set
created with series of values. To convert operations supported
one
C
C
the result range() function into list,
of by python with suitable example.
more function called list is needed( ). The [PTA-1; QY-2019]
list( ). function makes the result of range()Ans. A set is a mutable and an
as a list.
unordered collection of
elements without duplicates.
(ii) Syntax: List_Varibale =list ( range (0)
Set operations: The set operation such as
l
l
ia
tia
tia
tia
:
(ii) Example Union, Intersection, difference and symmetric
nt
en
id
id
Output: [2,4, 6, 8, 10] more sets [Govt. MQP-2019;PTA-2]
f
f
on
on
on
on
(iv) In the above code, list( ) function takes the Set A Set B
C
Thus, Even_List list has the elements of first
five even numbers.
Similarly, we can create any series of values
using range( ) function. The following
l
example explains how to create a list with () In python, the operator | is used to union of
ia
ia
ia
ia
squares of first 10 natural numbers. two sets. The function union()is also used
nt
t
en
en
en
natural numbers
Confidet
(ii) Example : Program to Join (Union) two
fid
fid
fid
on
on
on
for x in range(1,11):
s=x**2
nfic set_A={2,4,6,8}
set_B={A, 'B, C,D}
C
squares.append(s) U
set=set _A|set_B
prínt (squares) print(U_set)
Output: [1, 4,9, 16, 25, 36, 49, 64, 81, 100] Output :
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
Intersection : (Govt. MQP-2019; PTA-2]
Confidg Confider
C
C
() It includes the common elements in two Set A Set B
sets
Set A Set B
l
l
ia
tia
tia
tia
nt
en
en
en
de
fid
fid
fid
(ii) The caret (^) operator is used to symmetri
difference set operation in python. Th
on
on
on
on
(iü) The operator & is used to intersect two sets function symmetric difference( ) is als
C
C
in python. The function intersection( ) is used to do the sanme operation.
also used to intersect two sets in python.
(iil) Example : Program to insect two sets using (ii) Example Program to symmetri
intersection operator difference of two sets using caret operator
ide Confide
l
l
set_A=('A, 2,4, 'D'" set_A={'A, 2,4, D'}
ia
tia
tia
tia
set B=('AY'B,C, D} set_B={A, 'B, C, D'}
nt
en
en
en
print(set_A & set_B) print(set_A ^ set_B)
de
Output :
fid
fid
fid
Output :
'A, D}
on
on
{2, 4, 'B,'C}
on
on
Difference:
C
C
(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)
1. Write a program to remove duplicates from:
Set A Set B
list.
l
l
Ans. Method I
ia
tia
tia
tia
mylist = [2,4,6,8,8,4, 10]
onfider
nt
en
en
ide en
myset = set(mylist)
de
id
id
id
print(mylist)
f
f
:
Output {2, 4, 6, 8, 10}
on
on
on
on
(ii) The minus () operator is used to difference Method II:
C
C
set operation in python. The function def remove(duplicate):
difference( ) is also used to difference final_list=]
operation. for num in duplicate:
(ii) Example : Program to difference of two if num not in final_list:
l
l
ia
ia
ia
ia
en
en
de
fid
fid
print(set_A-set_B) print(remove(duplicate))
on
on
on
on
Symmetric diference:
value in a Tuple.
() It includes all the elements that are in
twoAns, 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
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
Output :
ent (i) In Python,_del_)
destructor.
del_) method is used as
onfider
Class Variable 1:5
oide General format of constructor :
l
l
Variable 2: 10 def_del_(self):
ia
tia
tia
tia
Class
Sum: 15 <statements>
nt
PART -
en
en
en
>>> IV
de
3. Find the error in the following programto get ANSWER THE FOLLOWINGQUESTIONS
fid
fid
fid
the given output? (5 MARKS)
on
on
on
on
class Fruits: 1. Write a menu driven program to add or delete
def_init_(self, fl, f2): stationary items. You should use dictionary to
C
C
self.f1=fI store items and the brand.
self.f2=f2
Ans. Code :
def display (self):
print("ruit I= %s, Fruit 2 = %s" stationary= tia
print("n1.Add Item \n2. Delete item \n3.Exit")
%(self.fl, self.f2))
fidet
l
l
ia
tia
tia
tia
F= Fruits ('Apple, Mango') cheint(input("\nEnter your choice:"))
nt
en
en
de
Edisplay) if(ch==1)
fid
fid
fid
Output: n=int(input("\nEnter the Number of
Fruit 1 = Apple, Fruit 2 = Mango Items to be added in the Dictionary:"))
on
on
on
on
Ans. In line No.8, del Fdisplay will not come. for i in range(n):
item=input("\nEnter an Item Name:")
C
C
4. What is the output of the following program?
class Greeting: brand=input("\nEnter the Brand Name:")
def init_(self, name): stationary[item]=brand
self. name = name print(stationary)
def display(self): elif(ch-2):
l
l
ia
tia
tia
tia
print("Good Morning", self._name)
ritem=input("\nEnter the item to be
fider
nt
en
en
obj.displayO
de
stationary.pop(ritem)
Ans. Good Morning Bindu Madhavan
id
id
id
print(stationay)
How do define constructor and destructor in
f
f
5. ch=int(input("nEnter your choice:")
on
on
on
on
Python? [PTA-4] Output :
:
Ans. Constructor
C
C
1. Add Item
) Constructor is the special function that 2. Delete item
is automatically executed when an object 3. Exit
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.
l
l
stationary shop :2
ia
ia
ia
ia
(ii) It must begin and end with double Enter an Item Name: Pen
identi
nt
underscore.
en
en
en
fid
fid
on
on
on
Destructor : :
Pen
() Destructor is also a special method gets (Pencil': Camlin'}
executed automatically when an object exit Enter your choice:3
from the scope.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(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
in developing and designing the parts of information's related to a particular type is
DBMS. stored in rows of that table.
l
l
ia
tia
tia
tia
(iii) End User : End users are the one who
(ii) Hence tables are also known as relations
nt
en
en
en
in a relational model. A relation key is
de
(iv) Database designers: They are responsible an attribute which uniquely identifies a
fid
fid
fid
for identifying the data to be stored in particular tuple (row in a relation (table)).
the database for choosing appropriate
on
on
on
on
Stu id Name Age Subj_id Name Teacher
structures to represent and store the data. Malar 17 C++ Kannan
PART - IV Suncar
2 16 2 Php Ramakrishnan
C
C
3 Velu 16 3 Python Vidhya
afider
l
l
Explain the different types of data model.
ia
tia
tia
tia
1. 92
1
2
[HY-2019]
nt
3 96
en
en
en
Ans. The different types of a Data Model: Relational Model
de
fid
fid
Network Model : Network database model is
Database Model, Entity Relationship Model, an extended form of hierarchical data model.
Model.
on
on
on
on
Object The difference between hierarchical and
Hierarchical Model : Network data model is :
C
C
(i) In hierarchical model, a child record has
() Hierarchical model was developed by IBM
as Information Management System. In only one parent node,
(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.
l
l
in many-to-many relationships.
ia
tia
tia
tia
(i) This model represents a one-to-many (iii) This model is easier and faster to access the
nfidel
nt
en
id
id
(iii) This model is mainly used in IBM Main
f
f
on
on
on
on
Frame computers.
This child has
Library Office Staff Room one parent node
C
C
School
l
ia
ia
ia
ia
en
en
Theory Lab
school (parent node)
de
fid
fid
Hierarchical Model
Relational Model
O
room (one to many relationship)
on
on
on
on
(i) The Relational Database model was first Entity Relationship Model. (ER mode):
proposed by E.F. Codd in 1970. Nowadays, () In this database model, relaionship are
C
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.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(ii) It was developed by Chen in 1976. This 2. Explain the different types of relationship
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
l
l
One-to-One Relationship
ia
tia
)
tia
tia
developer can easily understand the system
(i) One-to-Many Relationship
nt
en
en
en
(ii) Many-to -One Relationship
de
fid
fid
Doctor and Patient. (iv) Many-to-Many Rlationship
:
(i) One-to-One Relationship In One-to
on
on
on
on
(iv) Ellipse represents the attributes E.g. D-id,
One Relationship, one entity is related with
D-name, P-id, P-name. Attributes describes
C
C
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.
relationship in ER diagrams For example: A student can have only
fide! one exam number
idet
l
l
E.g. Doctor diagnosis the Patient
ia
tia
tia
tia
Student Exam No
nt
en
en
en
|Doctor Diagnosis Patient
de
fid
fid
fid
Tamilselvi 1001
on
on
on
on
D-id D-Name P-id P-Name Jayapandiyan 1002
C
C
ER model
: Sarojini 1003
Object Model
() Object model stores the data in the form of
objects, attributes and methods, classes and One to one Relationships
Inheritance.
l
l
:
(i) One-to-Many Relationship In One-to
ia
tia
tia
tia
(ii) This model handles more complex
Many relationship, one entity is related to
fide,
nt
en
en
en
applications, such as Geographic many other entities. One row in a table A
de
information System (GIS), scientific is linked to many rows in a table B, but one
id
id
id
experiments, engineering design and row in a table B is linked to only one row in
f
f
manufacturing.
on
on
on
on
table A.
(ii) It is used in file Management System. It
For example: One Department has many
C
C
represents real world objects, attributes staff members.
and behaviors. It provides a clear modular Staff
structure. It is easy to maintain and modify
the existing code. Department
Gajalakshmi
l
l
ia
ia
ia
ia
Shape
Bindhu éntia
nt
get _area(0
Computer
en
en
en
get perimeter()
de
Tamil Radha
fid
fid
fid
Ramesh
on
on
on
on
Maths
Rectangle Triangle
C
Malaiarasu
Circde Length Base
Radius
breath Height
One to Many Mapping
Object Model
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
(ii) Many-to-One Relationship : In Many- 3. Differentiate DBMS and RDBMS.
C
to-One Relationship, many entities can be Ans.
related with only one in the other entity.
Basis of
For example: A number of staff members DBMS RDBMS
one rows Comparison
working in Department. Multiple
l
l
ia
tia
tia
tia
in staff members table is related with only Expansion Database Relational
Management DataBase
nt
en
en
en
System Management
de
Staff Department
System
fid
fid
fid
Data storage Navigational Relational model
on
on
on
on
model (in tables). ie
Suganya ie data by data in tables as
C
C
Computer linked records row andcolumn
Bala
Maths Data Exhibit Not Present
Malarmathi
redundancy
Normalization Not RDBMS uses
l
l
ia
tia
tia
tia
performed normalization
nt
to reduce
en
en
en
Many to one Relationship
de
redundancy
: many
fid
fid
fid
(iv) Many-to-Many Relationship A
Data access Consumes Faster, compared
to-many relationship occurs when multiple more time to DBMS.
on
on
on
on
records in a table are associated with Keys and Does not use. used to establish
multiple records in another table.
C
C
indexes relationship.
Example 1: Customers and Product Keys are used in
Customers can purchase various products RDBMS.
and Products can be purchased by many Transaction Inefficient, Efficient and
l
l
customers management Error prone secure.
ia
tia
tia
tia
Example 2 : Students and Courses and insecure.
nt
en
en
en
A student can register for many Courses Distributed Not supported Supported by
de
id
id
Example Dbase, SQL server,
f
f
Example 3: Books and Student.
on
on
on
on
FoxPro. Oracle, mnysql,
Many Books in a Library are issued to many MariaDB,
C
C
students. SQLite.
Book Student
4. Explain the different operators in Relational
algebra with suitable examples.
Ans. Relational Algebra is divided into various groups
l
l
ia
ia
ia
ia
C++ Kalaivani
en
en
en
SELECT (symbol : o)
de
fid
fid
on
on
on
Theory :
python Sridevi UNION ()
C
INTERSECTION (0)
DIFFERENCE ()
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
fidex
C
C
SELECT (symbol : o):
Table B
(i) General form o (R) with a relation R and
a condition C on the attributes of R. Studio Name
(ii) The SELECT operation is used for selecting csl Kannan
l
l
a subset with tuples according to a given cs2 GowriShakaran
ia
tia
tia
tia
condition. cs3 Lenin
nt
en
en
en
(iii) Select filters out all tuples that do not satisfy
de
C. Result :
fid
fid
fid
STUDENT: TableAUB
on
on
on
on
Stu Studio Name
Name Course Year
dio
C
C
csl Kannan
csl Kannan Big Data II
cs2 GowriShankaran
cs2 Gowri
Shankar
R language I
Cs3
cS4
Lenin
Padmaja
énti
l
l
cs3 Lenin Big Data
ia
tia
tia
tia
Padmaja Python SET DIFFERENCE (Symbol : -):O
nt
cs4
en
en
en
Programming (i) The result of A - B, is a relation which
de
fid
fid
= “Big Data (STUDENT ) :
on
on
on
the attribute name in B.
PROJECT (Symbol : ):
C
C
:
(ii) Example 4 (using Table B)
() The projection eliminates all attributes of
the input relation but those mentioned in Result:
the projection list.
A- B
Table
(ii) The projection method defines a relation
nt
l
l
cs4Padmaja
ia
tia
tia
tia
that contains a vertical subset of Relation.
INTERSECTION (symbol : )ANB:
nt
en
en
de
id
id
Result : tuple that are in both in A and B. However,
f
f
A and B must be union-compatible.
on
on
on
on
Course
Big Data (i) Example 5 (using Table B)
C
C
R language Table A NB
Python Programming csl Kannan
:
UNION (Symbol U): cs3 Lenin
l
ia
ia
ia
(Symbol :X)
en
en
en
fid
fid
on
on
on
Table A
(m) A x B means A times B, where the relation
C
Studio Name
A and B have different attributes,
csl Kannan
(ii) This type of operation is helpful to merge
cs2 Lenin columns from two relations.
cs3 Padmaja
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
Confident
C
C
Table A Table B Table Ax Table B
Confideg
Cona
l
l
ia
tia
tia
tia
2 R
R
nt
en
en
en
S
de
3
fid
fid
fid
R
Table A=3
on
on
on
on
|Table B =2 3
C
C
Table A x B= 3 x 2 =6
ntia denial
Cartesian Product
3 R
l
l
ia
tia
tia
tia
5. Explain the characteristics of DBMS. [PTA-3, 5]
nt
en
en
de
Data stored into Tables Data is never directly stored into the database. Data is stored into tables, created
fid
fid
fid
inside the database. DBMS also allows to have relationship between tables which
makes the data more meaningful and connected.
on
on
on
on
Reduced Redundancy In the modern world hard drives are very cheap, but earlier when hard drives
C
C
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
that repetition is minimum.
Data Consistency On live data, it is being continuously updated and added, maintaining the
l
l
ia
tia
tia
tia
consistency of data can become a challenge. But DBMS handles it by itself.
nt
Support Multiple user DBMS allows multiple users to work on it(update, insert, delete data) at the
en
en
en
and Concurrent Accesssame time and still manages to maintainthe data consistency.
de
id
id
id
Query Language DBMS provides users with a simple query language, using which data can be
easily fetched, inserted, deleted and updated in a database.
f
f
on
on
on
on
Security The DBMS also takes care of the security of data, protecting the data from
C
C
unauthorized access. In a typical DBMS, we can create user accounts with
different access permissions, using which we can easily secure our data by
restricting user access.
DBMS Supports It allows us to better handle and manage data integrity in real world applications
l
ia
ia
ia
nt
t
en
en
en
fid
fid
fid
1 MARK
on
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
PART -I (i) The different states of our table can be
ANSWER THE FOLLOWING QUESTIONS
(3 MARKs)
idel saved at anytime using different names and
the rollback to that state can be done using
the ROLLBACK command.
l
l
What is a constraint? Write short note on
ia
tia
tia
tia
1. :
(ii) Example
Primary key constraint. [HY-2019]
nt
en
en
en
Ans. Constraints are used to limit the type of data that
de
can go into a table. This ensures the accuracy and UPDATE Student SET Name Mini'
fid
fid
fid
reliability of the data in the database. Constraints WHERE Admno=105;
could be either on a column level or a table level.
on
on
on
on
SAVEPOINT A;
Constraint is a condition applicable on a field or
5. Write a SQL statement using DISTINCT
C
C
set of fields.
keyword.
Primary Constraint;
Ans. (i) The DISTINCT keyword is used along
() This constraint declares a field as a Primary
with the SELECT command to eliminate
key which helps to uniquely identify a
duplicate rows in the table. This helps to
l
l
record.
ia
tia
tia
tia
eliminate redundant data.
(i) It is similar to unique constraint except
nt
en
en
en
(ii) For Example: SELECT DISTINCT Place
that only one field of a table can be set as
de
fid
fid
(ti) The primary key does not allow NULD PART - IV
on
on
on
on
values and therefore a field declared as ANSWER THE FOLLOWING QUESTIONS
primary key must have the NOT NULL
C
C
constraint. (5 MARKs)
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
l
l
Ans. Type of Constraints :
Constraints ensure
ia
tia
tia
tia
name><data type><size>;
database integrity, therefore known as database
nt
en
en
integrity constraints. The different type of
Ans. Data Definition Language :
de
Constraints are :
id
id
id
(i) Create Command : To create tables in the
Unique Constraint
f
f
database.
on
on
on
on
CREATE TABLE Student (Admno integer,
Name char(20), Gender char(1), Age Primary Key Constraint
C
C
integer); Constraint
(iü) Alter Command : Alters the structure of Default Constraint
the database.
ALTER TABLE Student ADD Address Check Constraint
l
l
ia
ia
ia
ia
(ii) Drop Command Delete tables from This constraint ensures that no two rows
en
en
en
(i)
database.
de
ide
fid
fid
fid
on
on
on
Ans. () 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.
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
:
Default Constraint:
C
(ii) CREATE TABLE Student
( (i) The DEFAULT constraint is used to assign
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
l
l
ia
tia
tia
tia
Gender char (1), default value will be assigned to the field.
(ii) Exanmple showing DEFAULT Constraint
nt
Age integer,
en
en
en
in the student table:
Place char (10),
de
:
(iil) CREATE TABLE Student
fid
fid
fid
(iii) The UNIQUE constraint can be applied
on
on
on
on
Admno integer NOT NULL PRIMARY
only to fields that have also been declared KEY,
C
C
as NOTNULL. Name char(20) NOT NULL,
(iv) When two constraints afe applied on a single Gender char( 1 ),
field, it is known as multiple constraints. In Age integer DEFAULT =“17",
the above Multiple constraints NOT NULL > Default Constraint
and UNIQUE are applied on a single field Place char(10),
l
l
ia
tia
tia
tia
Admno, the constraints are separated by a
nt
en
en
space and at the end of the field definition (ivy
assigned a default value of 17, therefore
de
fid
fid
constraints the field Admno must take user, it automatically assigns 17 to Age.
some value ie. will not be NULL and should
on
on
on
on
Check Constraint:
not be duplicated. (i) This constraint helps to set a limit value
C
C
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
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
table:O
l
l
except that only one field of a table can be
ia
tia
tia
tia
:
set as primary key. (ii) CREATE TABLE Student
nt
en
en
nfide en
(ii) The primary key does not allow NULL
de
values and therefore a field declared as Admno integer NOT NULL PRIMARY
id
id
id
KEY
primary key must have the NOT NULL
f
f
Name char(20) NOT NULL,
on
on
on
on
constraint. Gender char(1),
(ii) Example showing Primary Key Constraint Age integer (CHECK<=19)) > Check
C
C
in the student table: Constraint
(iv) CREATE TABLE Student: Place char(10),
);
Admno integer NOT NULL PRIMARY (ii) In the above example the check constraint
l
l
ia
ia
ia
ia
en
en
Gender char(1),
and logical operators for condition.
fid
fid
fid
Age integer,
Table Constraint :
Place char(10),
() When the constraint is applied to a group
on
on
on
on
() 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 defnition.
help us to uniquely identify a record, it is (ii) Let us take a new table namely Studentl
also set NOT NULL, therefore this field with the following fields Admno, Firstname,
l
ia
ia
ia
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(ii) CREATE TABLE Student 1 : 3. What are the components of SQL? Write the
( commands in each. [Govt. MQP-2019)
Admno integer NOT NULL, Ans. Components of SQL: SQL commands are
Firstname char(20), divided into five categories:
l
l
ia
tia
tia
tia
Lastname char(20), DDL - Data Definition Language
nt
Gender char(1),
en
en
en
Age integer, DML - Data Manipulation Language
de
Place char(10),
fid
fid
fid
PRIMARY KEY (Firstname, Lastname) DCL - Data Control Language
on
on
on
on
Table constraint
): TCL - Transaction Control Language
C
C
(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.
2. Consider the following employee table. Write Data Definition Language :
l
l
() The Data Definition Language (DDL)
ia
tia
tia
tia
SQL commands for the qtns. (i) to (v). [PTA-2]
consist of SQL statements used to define
nt
EMP ALLO
the database structure or schema.
en
en
en
NAME DESIG PAY
de
CODE WANCE
(i) It simply deals with descriptions of the
fid
fid
fid
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
on
on
on
on
databases.
P1003 Prasad Operator 12000 6500 (ii) SQL Commands which comes under Data
C
C
C1004 ManjimaClerk 8000 4500 Definition Language are :
M1005 RatheeshMechanic 200007000 Create To create tables in the database.
(1) To display the details of all employees in Alter Alters the structure of the
descending order of pay. database.
l
l
ia
tia
tia
tia
(ii) To display all employees whose allowance |Drop Delete tables from database.
nt
en
en
(iii) To remove the employees who are table, also release the space
de
id
id
mechanic.
(iv) To add a new row. Data Manipulation Language
f
f
on
on
on
on
(v) To display the details of all employees () A Data Manipulation Language (DML) is
a
who are operators. computer programming language used
C
C
for adding (inserting), removing (deleting),
Ans. (i) SELECT * FROM Employee ORDER BY
and modifying (updating) data in
PAY DESC; database.
SELECT * (ii) In SQL, the data manipulation language
(ii) FROM Employee WHERE
comprises the SQL-data change statements,
l
ia
ia
ia
en
en
(ii) DELETE FROM Employee WHERE (iii) SQL commands which comes under Data
de
fid
fid
DESIG='Mechanic;
(iv) INSERT INTO Employee (empcode, name, fide Insert Inserts data into a table
on
on
on
on
desig, pay, allowance) VALUES (S1002, Update Updates the existing data
within a table.
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
Data Control Language Ans. (i) GROUP BY clause :
) 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.
l
l
ia
tia
tia
tia
(Authorization). For example to know the number of male
nt
(i) The privileges are required for performing students or female students of a class,
en
en
en
all the database operations such as creating the GROUP BY Clause may be used. It is
de
fid
fid
fid
sequences, views of tables etc. mostly used in conjunction with aggregate
(iii) SQL commands which come under Data functions to produce summary reports
on
on
on
on
Control Language are: from the database.
The syntax for the GROUP BY clause is
C
C
Grant Grants permission to one or
more users to perform specific SELECT Kcolumn-names> FROM <table
name> GROUP BY <column-name>
tasks.
HAVING condition);
RevokeWithdraws the access To apply the above command on the
l
l
permission given by the
ia
tia
tia
tia
student table:
GRANT statement.
nt
en
en
Transactional Control Language :
BY Gender;
de
fid
fid
The following command will give the
commands are used to manage transactions below given result :
in the database. These are used to manage
on
on
on
on
the changes made to the data in a table by Gender
C
C
DML statements.
(i) SQL command which come under Transfer M
Control Language are : F
CommitSaves any transaction into the SELECT Gender, count(*) FROM
l
l
database permanently. Student GROUP BY Gender:
ia
tia
tia
tia
Restores the database to last
Roll
fide
nt
Gender count(*)
en
en
en
back commit state. M 5
de
id
id
3
point transaction so that you can (ii) ORDER BY clause:
f
f
on
on
on
on
rollback. The ORDER BY clause in SQL is used
Data query language : to sort the data in either ascending
C
C
or descending based on one or more
(i) The Data Query Language consist of
columns.
commands used to query or retrieve data
from a database. (a) By default ORDER BY sorts the data
in ascending order.
(ii) One such SQL command in Data Query
l
ia
ia
ia
t
en
en
en
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
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
The above student table is arranged as field.
l
l
ia
tia
tia
tia
follows : Ans. CREATE TABLE employee (empno ineger
NOT NULL PRIMARY KEY, ename char(30)
nt
en
en
en
NOT NULL, desig char(30),doj datetime, basic
de
fid
fid
101 Adarsh M 18 Delhi 5. Prepare a list of all employees who are
on
on
on
on
102 Akshith M 17 Bangalore Managers..
Ans. SELECT*FROM employee WHERE desig =
C
C
100 Ashish M 17 Chennai
'Managers';
103
106
Ayush
Devika
M
F
18
19
Delhi
Bangalore
PTA> QUESTIONS AND ANSWERS ntal
1
MARK
l
l
107 Hema F 17 Chennai
ia
tia
tia
tia
1. Pick odd one :
[PTA-1)
Revathi Chennai
nt
105 F 19
(a) Commit (b) Roll back
en
en
en
de
fid
fid
employee having any five fields and create a [Ans. (d) Revokel
table constraint for the employee table. 2. Pick Odd one: [PTA-2]
on
on
on
on
Ans. CREATE TABLE employee (a) INSERT (b) DELETE
C
C
( (c) UPDATE (d) TRANCATE
empcode integer NOTNULL, |Ans. (D) TRANCATE)
name char(20),
3. The TCL Command used to restores the
desigchar(20),
Pay integer, tial database to the last commit state. [PTA-3]
l
l
(a) Commit (b) SavePoint
ia
tia
tia
tia
allowance integer, (c) Insert (d) Rollback
nt
en
en
en
PRIMARY KEY (empno) [Ans. (d) Rolback]
de
id
id
HANDS ON EXPERIENCE from a table in a database: [PTA-3]
f
f
on
on
on
on
(a) SELECT (b) CREATE
(c) DISTINCT (d) ORDER BY
1. Create a query of the student table in the
C
C
following order of field name, age, place and |Ans. (a) SELECT]
admno. 5. The SQL command "Truncate' comes under:
Ans. CREATE TABLE Student (Name char(30), age [PTA-4]
integer, place char(30), admno integer)); (a) DDL (b) DML
l
ia
ia
ia
2..
JAns. (a) DDLJ, O
students of age more than 18 with unique city.
nt
t
en
en
en
Ans. SELECT FROM student WHERE age >= 18 6. Match the following: [PTA-5]
de
fid
fid
on
on
on
Ans. CREATE TABLE employee (empNo integer, (a) a-iv, b-iii, c-i, d-i (b) a-iv,b-i, c-i, d-ii
ename char(30), desig char(30), doj datetime, (c) a-i, b-iy, c-iii, d-ii (d) a-i, b-i, c-iy, d-ii
basic integer); [Ans. (b) a-iv, b-i, c-ii, d-iii]
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
Output :
PART - IV
('SNO, NAME, CITY) ANSWER THE FOLLOWING QUESTIONS
[12101, RAM, CHENNAI] (5 MARKS)
l
l
ia
tia
tia
tia
['12102', 'LAVANYA, "TIRUCHY] Differentiate Excel file and CSV file. PTA-2]
nt
en
en
en
Ans.
de
fid
fid
CSV
4. What is the difference between the write mode Excel is a binary file that CSV format is a plain
on
on
on
on
and append mode. [PTA-2, 5]I holds information text format with a
about all the worksheets in series of values
Ans. The 'w' write mode creates a new file. If the file
C
C
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
XLS files can only be read CSV can be opened
end of the file if the file already exists otherwise
by applications with any text editor
l
l
creates a new one.
ia
tia
tia
tia
that have been especially in Windows like
written to read their format, notepad, MS Excel,
nt
en
en
DictReader() function? and can only be written in OpenOffice, etc.
de
fid
fid
Ans. Reader):
Excel is a spreadsheet that CSV is a format
on
on
on
on
) The reader function is designed to take saves files into its for saving tabular
each line of the file and make a list of all own proprietary format viz. information into a
C
C
xls or xlsx delimited text file with
columns.
extension .csv
(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,
l
l
() and comma ). and it also consumes
ia
tia
tia
tia
pipe data
less memory
nt
en
en
de
id
id
Ans.
fmtparams)
f
f
on
on
on
on
Mode Description
DictReaer):
Open a file for reading. (default)
C
C
(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
separated value in this line as a dictionary exists.
key. 'x Open a file for exclusive creation. If the fle
l
l
ia
ia
ia
ia
en
en
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
Write the different methods to read a File in
3.
Python.
Ans. Read a CSV File Using Python :
Program:
#importing csv ident
import csv
There are two ways to read a CSV fle.
l
l
ia
tia
tia
tia
(i) Use the csv module's reader function #opening the csv file which is in different
Co
nt
en
en
en
(ii) (Use the DictReader class.
de
fid
fid
#other way to open the file is f= (c:l\pyprgl
on
on
on
on
samplel.csv, r)
reader = csv.reader(F)
C
C
reader () function Dict Reader class
# printing each line of the Data row by row
CSV Module's Reader Function :
l
ia
tia
tia
tia
Output :
function is designed to take each line of the
nt
en
en
en
file and make a list of all columns. ['SNO', NAME, 'CITY]
de
(ii) Then, you just choose the column you want ['12101, 'RAM, 'CHENNAI]
fid
fid
fid
the variable data for. Using this method [12102, LAVANYA, TIRUCHY]
on
on
on
on
one can read data from csv files of different
formats likequotes (""), pipe () and comma
[12103, 'LAKSHMAN, 'MADURAI]
C
C
). CSV files - data with Spaces at the beginning
The syntax for csv.reader) is Consider the following file "'sample2.csv"
cSv.reader(fleobject,delimiter,fmtparams) containing the following data when opened
where through notepad
l
l
ia
tia
tia
tia
(iii) file object : passes the path and the mode Topicl, Topic2, Topic3,
nt
en
en
en
of the file one, two, three
de
id
an
id
,
containing the standard dilects like | etc
f
f
The following program read the file through
on
on
on
on
can be omitted.
Python using "csv,reader()".
(v) fmtparams: optional parameter which
C
C
import csv
help to override the default values of the
dialects like skipinitialspace,quoting etc. csv.register_dialect('myDialect' delimiter =
can be omitted. skipinitialspace=True)
l
ia
ia
ia
ia
onfident
en
en
en
beginning
fid
fid
fid
print(row)
CSV file- data with quotes
Fclose()
on
on
on
on
CSV file with default delimiter comma (): The ('Topicl', "Topic2', "Topic3]
following program read a file called "samplel.,
csv with default delimiter comma ()) and print ['one', 'two', three']
row by row. ['Examplel1, "Example2, 'Example3]
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
(i) These whitespaces in the data can be CSV files with Custom Delimiters :
removed, by registering new dialects using
csv.register dialect) class of csv module. nfide() You can read CSV file having custom
delimiter by registering a new dialect with
(i) A dialect describes the format of the csv file
l
l
the help of csv.register_dialect().
ia
tia
tia
tia
that is to be read.
nt
en
en
en
(ii) Indialectstheparameter"skipinitialspace"
de
fid
fid
delimiter. 12102 Meena Kovai
on
on
on
on
12103 Ram Nellai
CSV File-Data With Quotes :
Ayush
C
C
(i) You can read the csv file with quotes, by 103 M
registering new dialects using cSV.register_ 104 Abinandh M
dialect() class of csv module.
(i) In the following file called "'sample4.csv",
(ii) Here, we have quotes,csv file with following each column is separated with
fide (Pipe
l
l
ia
tia
tia
tia
data. symbol)
nt
SNO, Quotes
en
en
en
import csv
de
fid
fid
started'"
with open(c:llpyprgl lsample4.csv,r) as f:
on
on
on
on
2. "Excellence is a continuous process and not
an accident." reader = cSv.reader(f, dialect='myDialect')
C
C
The following Program read "quotes.csv" file, for row in reader:
where delimiter is comma () bUt the quotes are print(row)
within quotes ("").
fclose()
l
l
import csv
ia
tia
tia
tia
OUTPUT
csv.register_dialect('myDialect', delimiter =
onfidet
nt
en
en
quoting=csv.QUOTE_ALL,
de
12101,'Arun', 'Chennai']
id
id
id
skipinitialspace-True)
[12102', Meena, Kovai']
f
f
on
on
on
on
f-open(cl(pyprgllquotes.csv' r')
[12103, 'Ram', Nellai']
reader csv.reader(f, dialect='myDialect')
C
C
4. Write a Python program to write a CSV File
for row in reader: with custom quotes.
print(row) Ans. import csv
OUTPUT: info = [[SNO) Person, DOB],
l
l
ia
ia
ia
ia
t
en
en
en
started.]
[2, Sowmya,19/2/1998'],
de
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
with open(clipyprgllch]3l\person.csv, 'w) as f (v) Each field may or may not be enclosed in
writer = csv.writer(f, dialect='myDialect') double quotes. If fields are not enclosed
for row in info: fide with double quotes, then double quotes
may not appear inside the fields.
l
l
ia
tia
tia
tia
writer,writerow(row) Example:
nt
en
en
en
double quotes
de
OUTPUT:
fid
fid
fid
"SNO; "Person",; "DOB" "1", "Madhu", Black,White, Yellow #Field data without
"Sowmya,
double quotes
"18/12/2001" "2",
on
on
on
on
"19/2/1998"
"3", "Sangeetha", "20/3/1999" "4", "Eshwar",
(vi) Fields containing line breaks (CRLF),
double quotes, and commas should be
C
C
"21/4/2000" "5", "Anand", "22/5/2001"
enclosed in double-quotes.
5. Write the rules to be followed to format the Example:
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
l
l
ia
tia
tia
tia
file: Red, Blue, Green
nt
en
en
Each record (row of data) is to be located
then a double-quote appearing inside a
de
fid
fid
by pressing enter key. field must be preceded with another double
quote.
on
on
on
on
Example: J
Example:
XXX,yyy
C
C
"Red, " "Blue, “Green'; # since double
Jdenotes enter Key to be pressed quotes is a field value it is enclosed with
(ii) The last record in the file may or may not another double quotes, White
,
l
ia
tia
tia
tia
PPP, qqq«
nt
en
en
yYy, xxX
following Namelist.csv file and sort the data
de
(ii) There may be an optional header line in alphabetically order of names in a list and
id
id
id
appearing as the first line of the file with the display the output.
f
f
same format as normal record lines. The
on
on
on
on
header will contain names corresponding A B
C
C
to the fields in the file and should contain SNO NAME OCCUPATION
thesame number of fields as the records in 2 NIVETHITHA ENGINEER
the rest of the file. 3 2 ADHITH DOCTOR
Example:
l
l
4 3 LAVANYA SINGER
ia
ia
ia
ia
field_namel,field_name2,field_name34
5 4 VIDHYA TEACHER
nt
aaa,bbb,ccC«J
en
en
en
fid
fid
Line Feed)
data csv.reader(open('c:\\PYPRGI\NameList.
(iv) Within the header and each record, there
on
on
on
on
csv))
may be one or more fields, separated by
next(data)
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
PART -IV (i) To use sys.argv, you will first have to
import sys. The first argument, sys.argv [0],
ANSWER THE FOLLOWING QUESTIONS is always the name of the program as it
was invoked, and sys.argv(1] is the first
(5 MARKs)
l
l
ia
tia
tia
tia
argument you pass to the program (here it
1. Write any 5 features of Python. [PTA-3] is the C++ file).
nt
en
en
en
Ans. (i) Python uses Automatic Garbage Collection. (i) Python's OS Module :
de
fid
fid
(iii) Python runs through an interpreter. way of using operating system dependent
functionality.
on
on
on
on
(iv) Python code tends to be 5 to l0 times
shorter than that written in C++.
(ii) The functions that the OS module allows
C
C
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 Os.system):
argument of any type, and return multiple (i) Execute the C++ compiling command (a
l
l
values without any kind of declaration
ia
tia
tia
tia
string contains Unix, C command which
beforehand
also supports C++ command) in the shell
nt
en
en
en
(Here it is Command Window).
de
fid
fid
Python <filename.py>-<i><C++filename compiler should be invoked.
without cpp extension> (iv) Command : os.system (g++ + <varaiable_
on
on
on
on
Ans. Python <filename.py> -i <Ct+ filename without namel> -<mode>'+ <variable_name2:>
C
C
cpp extension> ()os.system function system() defined
where, in os module
(ii) g+t General compiler to
Python Keyword to execute the
Python program from tia) compile C++ program
under Windows Operating
l
l
command-line
ia
tia
tia
tia
system.
filename.py Name of the Python
nt
en
en
en
(iii) variable_namel Name of the C++ file
program toexecuted
de
without extension.cpp in
id
id
id
input mode string format
f
f
C++ filename Name ofC++ file to be (iv) mode To specify input or output
on
on
on
on
without cpp compiled and executed mode. Here it is o prefixed
with hyphen.
C
C
extension
Python getopt module :
3. What is the purpose of sys, os,getopt module
in Python? Explain. () The getopt module of Python helps you to
parse (split) command-line options and
Ans. (i) Python's sys module : This module
l
ia
ia
ia
by the interpreter and to functions that (i) This•module provides two functions to
nt
t
en
en
en
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
argv -
This is the argument list of 4. Write the syntax for getopt() and explain its
C
values to be parsed (splited). In our arguments and return values. [PTA-2, 5)
program the complete command will Ans. Python getopt Module :
be passed as a list. ) The getopt module of Python helps you to
co
- parse (split) command-line options and
options This is string of option
l
l
ia
tia
tia
tia
letters that the Python program arguments.
nt
en
en
en
enable command-line argument parsing.
with options (like" or 'o) that
de
fid
fid
followed by a colon ().
command-line options and parameter list.
Here colon is used to denote the Following is the syntax for this method -
on
on
on
on
mode. <opts>,<args>=getopt.getopt(argv, options,
C
C
long_options This parameter is [long options|)
a
passed with list of strings. Argument Here is the detail of the parameters -
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
l
l
In our program the C++ file name complete command will be passed as a list.
ia
tia
tia
tia
will be passed as string and 'i' also will (i) options :This is string of option letters that
nt
en
en
en
be passed along with to indicate it as the Python program recognize as, for input
de
fid
fid
that followed by a colon (). Here colon is
(iv) getopt() method returns value consisting
used to denote the mode.
on
on
on
on
of two elements.
Each of these values are stored separately
(ii) long _options: This parameter is passed
C
C
(v)
with a list of strings. Argument of Long
in two different list (arrays) opts and args.
options should be followed by an equal sign
(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 '? also will be
at all not splitted because of wrong path or passed along with to indicate it as the input
l
l
ia
tia
tia
tia
mode. file.
nt
en
en
(vi) getopt) method returns value consisting of
de
error in splitting strings by getopt(). two elements. Each of these values are stored
id
id
id
(viil) Example separately in two diferent list (arrays) opts and
f
f
opts, args = getopt.getopt (argv, args. Opts contains list of splitted strings like
on
on
on
on
(vi)
"i:",['ifile=) mode, path and args contains any string if at
C
C
- all not splitted because of wrong path or mode.
where optscontains (i, 'c:\\pyprgl args will be an empty array if there is no error in
p4)] splitting strings by getopt().
-
-i: option nothing but mode should
be followed by :
-
toexecute the C++ file p4 in command line will
ia
ia
ia
ia
en
en
our
de
fid
fid
oic
on
on
on
on
file.
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
In our examples since the entire command line
HANDS ON EXPERIENCE
commands are parsed and no leftover argument,
the second argument args will be empty []. 1. Write a C++ program to create a class called
If args is displayed using print(0 command it
onfi
Student with the following details
l
l
ia
tia
tia
tia
displays the output as []. Protected member
nt
Rno integer
en
en
en
5. Write a Python program to execute the
Public members
de
fid
fid
#include <iostream> assign to Rno
on
on
on
on
using namespace std; void Writeno(); To display Rno.
int main) The class Test is derived Publically from the
C
C
Student class contains the following details
{cout<<«WELCOME";
return(0);
Antial Protected member
Markl float
Mark2 float
The above C++ program is saved in a file
l
l
Public members
ia
tia
tia
tia
welcome.cpp void Readmark(float, float); To accept markl
nt
and mark2
en
en
en
Ans. #Now select FileNew in Notepad and type the
de
fid
fid
Create a class called Sports with the following
# Program that compiles and executes a .cpp file
detail
on
on
on
on
# Python main.py -i welcome
Protected members
import sys, os, getopt score integer
C
C
def main(argv): Public members
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
l
l
opts, args =getopt.getopt (argv, "i:"[ifle=])
ia
tia
tia
tia
and Sports class contains the following details
for o, a in opts: Private member
der
nt
en
en
en
ifo in (""--ifile"): Total float
de
id
id
void display() assign the sum of markl, mark,
f
f
exe file
=a+'.exe' score in total.
on
on
on
on
run(cpp_ile, exe_file) invokeWriteno(), Writemark() and Writescore().
C
C
def run(cpp_file, exe_file): Display the total also.
Save the C++ program in a fle called hybrid.
print("Compiling" + cpp_file)
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+t+ program.
l
l
ia
ia
ia
ia
print(" #include<iostream>
nt
en
en
print
class student
Confider
de
OS.system(exe_file)
fid
fid
fid
print protected:
name= nfi
on
on
on
on
Co public:
C
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
PART - IV 2. Write the Python script to display all therecords
of the following table using fetchmany()
ANSWER THE FOLLOWING QUESTIONS
(5 MARKS) Icode Item Name Rate
l
l
ia
tia
tia
tia
1. Write in brief about SQLite and the steps used 1003 Scanner 10500
to use it.
nt
en
en
en
Ans. (i) SQLite is a simple relational database
de
fid
fid
1008 Monitor 15000
files or even in the internal memory of the
Mouse
on
on
on
on
1010 700
computer.
(ii) It is designed to be embedded in Ans. Assume database name, is shop.db and table
C
C
applications, instead of using a separate name is electronics for the given table.
database server program such as MySQLor Python Script :
Oracle. import sqlite3
Advantages : connection= sqlite3.connect ("shop.db")
cursor connection. cursor ()
l
l
(i) SQLite is fast, rigorously tested, and
ia
tia
tia
tia
cusrsor. execute ("SELECT* FROM
flexible, making it easier to work. Python
nt
en
en
en
has a native library for SQLite. electronics")
result = Cursor. fetchall )
Cont
de
To use SQLite,
fid
fid
fid
Step 1 : import sqlite3 print (* result, sep = "\n")
Output :
on
on
on
Displaying All the Records
) method and pass the name of (1003, 'Scanner, 10500)
C
C
the database file
(1004, 'Speaker', 3000)
Step 3 Set the cursor object cursor
:
(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
l
l
What is the use of HAVING clause? Give an
ia
tia
tia
tia
3.
accessed. If the database already exists the
example python script. [PTA-5]
nt
en
en
Ans. HAVING clause is used to filter data based on
Python will open a new database file with
de
id
id
condition but can be used only with group
(ii) Cursor in step 3 is a control structure used
f
f
functions. Group functions cannot be used in
on
on
on
on
to traverse and fetch the records of the WHERE Clause but can be used in HAVING
database. clause.
C
C
(iv) Cursor has a major role in working with Example :
Python. All the commands will be executed import sqlite3
using cursor object only. connection = sqlite3.connect("Academy.db")
(v) To create a table in the database, create an cursor = connection.cursor()
l
l
ia
ia
ia
ia
GENDER,CÓUNT(GENDER)
en
en
en
(vi) For executing the command use the cursor GROUP BY GENDER HAVING
de
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
4. Write a Python script to create a table called Ans. (i) import sqlite3
ITEM with following specification. connection = sqlite3.connect("ABC.db")
Add one recôrd to the table.
Name of the database ABC
fide cursor.execute("SELECT Supplier.Name,
Supplier.City,Item.Item Name FRÔM
l
l
ia
tia
tia
tia
Name of the table Item Supplier,Item WHERE Supplier.Icode=
nt
en
en
en
Delhi")
de
Icode integer and act as primary key s = i[0] for Iin cursor.
fid
fid
fid
Item Name Character with length 25 description ]
on
on
on
on
Rate Integer print(s)
Record to 1008, Monitor, 15000 result = cursor.fetchall()
C
C
r
for in result:
be added
print r
Ans. import sqlite3 Output:
connection = sqlite3 .connect ("ABc.db")
[Name, City, 'Item Name']
cursor = Connection . cursor () [Anu', 'Bangalore, 'Scanner]
l
l
ia
tia
tia
tia
sql_command CREATE TABLE Item ['Shahid', 'Bangalore', 'Speaker']
nt
en
en
¿onfi [(Girish', Hydrabad', 'Monitor'}
de
fid
fid
(sql_command) [Lavanya', 'Mumbai', (CPU]
on
on
on
on
sql_command ="" "INSERT INTO Item (Icode, (ii) import sqlite3
connection = sqlite3.connect("ABC.db")
Item_name, Rate)
C
C
cursor.execute("UPDATE Supplier ST
VALUES (1008, "Monitor", 15000); SuppQty= SuppQty + 40 WHERE Name =
cursor.execute (sql_command) 'Akila' ")
connection.commit () cursor.commit()
connection.close () result = cursor.fetchall()
l
l
print (result)
ia
tia
tia
tia
print ("TABLE CREATED")
connection.close()
der
nt
Output :
en
en
en
OUTPUT:
de
TABLE CREATED
(S004, 'Akila', Hydrabad', 1005, 235)
id
id
id
5. Consider the following table Supplier and
f
f
item .Write a python script for (i) to (ii) HANDS ON EXPERIENCE
on
on
on
on
SUPPLIER 1. Create an interactive program to accept the
C
C
details from user and store in a csv file using
Suppno Name City Icode SuppQty
Python for the following table.
-
SO01 Prasad Delhi 1008 100 Database name; DBI
Table name : Customer
SO02 Anu Bangalore1010 200
l
l
ia
ia
ia
ia
SO03 Shahid Bangalore 1008 175 Cust Cust Address Phone City
nt
Id Name no
en
en
en
fid
fid
on
on
on
(i) Display Name, City and Itemname of CO12 Hrithik 7/2 26121949 Delhi
suppliers who do not reside in Delhi. Vasant
(i) Increment the SuppQty of Akila by 40. Nagar
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
Ans. Ans. import matplotlib.pyplot as plt
slices > [7, 2, 2, 13]
Epic Graph
Another Line! whoa activities = ['sleeping'", "eating'", "working",
l
l
Example One 1
"playing",
ia
tia
tia
tia
Example two
y.l.1f%%)
en
en
en
plt.title ("Interesting Graph Checkit out")
de
fid
fid
fid
plt.show()
PART - IV
on
on
on
on
6 10
bar number
ANSWER THE FOLLOWING QUESTIONS
C
C
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]
and interpret the data easily. Ans. Matplotlib allows you to create different kinds of
l
l
ia
tia
tia
tia
(ii) It makes complex data understandable and
plots ranging from histograms and scatter plots
nt
usable.
en
en
en
to bar graphs and bar charts.
(i) Various Charts in Data Visualization helps
de
fid
fid
more variables. (i) A Line Chart or Line Graph is a type of
on
on
on
on
3. Write the coding for the following: chart which displays information as a series
a. To check if PIP is Installed in your PC. of data points called 'markers' connected
C
C
b. To Check the version of PIP installed in by straight line segments.
your PC. (ii) A Line Chart is often used to visualize
C. To list the packages in matplotlib. a trend in data over intervals of time - a
Ans. a. Tocheck if PIP is Installed in your PC: time series – thus the line is often drawn
l
l
ia
tia
tia
tia
) In command prompt type pip- version. chronologically.
(i) Ifit is installed already, you will get version.
iden
nt
(ii) Example
en
en
en
(ii) Command :Python - m pip install -U pip.
de
de
id
id
your P: importmatplotlib.pyplot as plt
f
f
years = [2014, 2015, 2016, 2017, 2018]
on
on
on
on
C:\Users| YourName\AppData\Local\
Programs\ Python\ Python 36-32\ total _populations = [8939007, 8954518,
C
C
Seripts>pip-version.
:
8960387, 8956741, 8943721]
To list the packages in matplotib
plt.plot (years, total populations)
C:\Users\YourName\App Data\ Local\
Programs\Python\ Python 36-32\Scripts> plt.title ("Year vs Population in India")
pip list plt.xlabel ("Year")
l
l
ia
ia
ia
ia
4. Write the plot for the following pie chart plt.ylabel ("Total Population")
enti
nt
t
en
en
en
output. plt.show)
de
In this program,
Cofide
fid
fid
fid
on
on
on
54.2%
Plt.xlabel) > specifies label for X-axis
C
83%
83%
Plt.ylabel()0 > specifies label for Y-axis
ctng
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
:
Output Output
8960000
onio
Year vs Population in India
ide Figure
MARKS
1
l
l
ia
tia
tia
tia
89550004
nt
en
en
en
8950000 RANGE
de
fid
fid
fid
8945000
on
on
on
on
8940000
204
2014.4 2014.5 2015.0 2015.5 2016.0 2016.6 2017.0 2017.7 2018.o
C
C
Year
:
Bar Chart
(i) A BarPlot (or BarChart) is one of the
most common type of plot. It shows the e
l
l
Pie Chart:
ia
tia
tia
tia
relationship between a numerical variable
Pie Chart is probably one of the most
nt
en
en
common type of chart. It is a circular
de
fid
fid
rectangular bars. Each bar has a height graphic which is divided into slices to
on
on
on
on
corresponds to the value it represents. The illustrate numerical proportion.
bars can be plotted vertically or horizontally. The point of a pie chart is to show the
C
C
(ii)
(iii) It's useful when we want tocompare a given
relationship of parts out of a whole. To
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.
l
l
ia
tia
tia
tia
(iv) Example : (iii) The autopct parameter allows us to display
nt
en
en
en
import matplotlib.pyplot as plt the percentage value using the Python
de
id
id
#Our data
f
f
labels "TAMIL";, "ENGLISH", "MATHS", :
on
on
on
on
(iv) Example
"PHYSICS", "CHEMISTRY", "CS")
import matplotlib.pyplot as plt
C
C
usage = [79.8, 67.3,77.8, 68.4, 70.2, 88.5]
# Generating the y positions. Later, well sizes = [89, 80, 90, 100, 75)
use them to replace them with labels. labels = ["Tamil", "English", "Maths",
Y_positions = range (len(labels))
l
"Science", "Social"]
ia
ia
ia
ia
en
en
"%.2f")
fid
fid
fid
on
on
on
plt.show()
l
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
Output :
3. Explain the purpose ofthefollowing functions:
Figure 1
o
a. plt.xlabel
b. plt.ylabel
l
l
ia
tia
tia
tia
C. plt.title
nt
Tamil d. plt.legend()
en
en
en
18,43
de
20.51
e. plt.show()
fid
fid
fid
20.74
Ans. a. Specifies label for x-axis
17.28
on
on
on
on
b. Specifies label for y-axis
23.04 Social
C
Science
plot title.
d. Invoke the default legend with plt
e. Display the plot
2. Explain the various buttons in a matplotlib
l
l
HANDS ON EXPERIENCE
ia
tia
tia
tia
window. [PTA-5]
nt
:
Ans. Buttons in the output In the output figure,
en
en
en
Create a plot. Set the title, the x and y labels for
de
you can see few buttons at the bottom left corner. both axes.
fid
fid
fid
Let us see the use of these buttons. Ans. import matplotlib.pyplot as plt
Configure
x= [1, 2, 3]
on
on
on
on
Subplots
Home Button Pan Axis Button Button
y= [5,7, 4]
C
C
plt.plot(x,y)
plt.xlabel('x-axis')
Zoom Save the
Forward/ Back Buttons Button Figure Button plt.ylabel('y-axis')
Home Button The Home Button will plt.title(LINE GRAPH)
()
l
l
help one to begun navigating the chart. If plt.show)
ia
tia
tia
tia
LINE GRAPH
you ever want to return back to the original
nt
144
Confide)
en
en
en
view, you can click on this.
de
id
id
12
can be used like the Forward and Back
f
f
buttons in browser. Click these to move
on
on
on
on
10
back to the previous point you were at, or
sx-A
C
C
forward again.
8
(ii) Pan Axis This cross-looking button
allows you to click it, and then click and
64
drag graph around.
(iv) Zoom The Zoom button lets you click on
l
l
ia
ia
ia
ia
en
en
X- Axis
require a left click and drag. Zoom out with
de
fid
fid
on
on
on
l
ia
ia
ia
ia
t
t
en
en
en
en
fi
fi
fi
on
on
on
on
C
C
l
l
ia
tia
tia
tia
nt
en
en
en
de
LINE GRAPH
fid
fid
fid
1. Draw the output for the following Python
code. [PTA-3]
14
ConNc
on
on
on
on
import matplotlib.pyplot as plt 12
a= (1, 2, 3]
C
C
4]
b=(5,7, 10
x= [1, 2, 3] Axis
1') 8
plt.plot(a,b, label=Lable
l
l
ia
tia
tia
tia
plt.plot(x,y, label='Lable 2')
nt
plt.xlabel(X-Axis') 6
ential
en
en
en
plt.ylabel(Y-Axis')
al
de
plt.legend)
fid
fid
fid
4
nfe
125 2.50 2.75
on
on
on
on
X- Axis
C
C
2. What are the key differences between Histogram and Bar graph? [PTA-4)
Ans.
Histogram Bar graph
l
l
ia
tia
tia
tia
() Histogram refers to a graphical A bar graph is a pictorial representation of data
that uses bars to compare different categories
nt
en
id
id
id
(i) A histogram represents the frequency Conversely, a bar graph is a diagrammatic
f
f
distribution of continuous variables. comparison of discrete variables.
on
on
on
on
(ii) Histogram presents numerical data. Bar graph shows categorical data.
C
C
(iv) Items of the histogram are numbers, which
are categorised together, to represent ranges
of data.
As opposed to the bar graph, items are
Considered as individual entities. ide
A histogram, this cannot be done, as they are In the case of a bar graph, it is quite common
l
(v)
ia
ia
ia
ia
shown in the sequence of classes. to rearrange the blocks, from highest to lowest.
nt
t
en
en
en
fid
fid
on
on
on
on
C
C
l
l
ia
ia
ia
ia
t
t
en
en
en
en