0% found this document useful (0 votes)
56 views145 pages

Complete Material

Uploaded by

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

Complete Material

Uploaded by

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

Contents

Chapter Title Page

1 Functions 1

2 Data Abstraction 7

3 Scoping 12

4 ALGORITHMIC STRATEGIES 18

5 Python – Variables and Operators 25

6 Control Structures 34

7 Python Functions 42

8 Strings and String manipulations 54

9 List, Tuples, Set and Dictionary 62

10 Python Classes and objects 71

11 Database Concepts 77

12 Structured Query Language (SQL) 89

13 Python and CSV files 101

14 Importing C++ Programs in Python 108

15 Data Manipulation through SQL 114

16 Data Visualization using pyplot: Line chart, Pie chart and Bar 122
charts

Annexure 1 TECH EASY ASSORTMENT 128

Annexure 2 MARCH 2024 PUBLIC QUESTION PAPER 144


1 FUNCTION

Part - I
Choose the best answer: (1 Mark)
1. The small sections of code that are used to perform a particular task is called
(A) Subroutines (B) Files (C) Pseudo code (D) Modules
2. Which of the following is a unit of code that is often defined within a greater code structure?
(A) Subroutines (B) Function (C) Files (D) Modules
3. Which of the following is a distinct syntactic block?
(A) Subroutines (B) Function (C) Definition (D) Modules
4. The variables in a function definition are called as
(A) Subroutines (B) Function
(C) Definition (D) Parameters
5. The values which are passed to a function definition are called
(A) Arguments (B) Subroutines (C) Function (D) Definition
6. Which of the following are mandatory to write the type annotations in the function
definition?
(A) {} (B) () (C) [] (D) <>
7. Which of the following defines what an object can do?
(A) Operating System (B) Compiler (C) Interface (D) Interpreter
8. Which of the following carries out the instructions defined in the interface?
(A) Operating System (B) Compiler (C) Implementation (D) Interpreter
9. The functions which will give exact result when same arguments are passed are called
(A) Impure functions (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
10. The functions which cause side effects to the arguments passed are called
(A) Impure function (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
Part - II
Answer the following questions: (2 Marks)
1. What is a subroutine?
Subroutines are small sections of code that are used to perform a particular task that can
be used repeatedly. In Programming languages these subroutines are called as Functions.
2. Define Function with respect to Programming language.
A function is a unit of code that is often defined within a greater code structure.
Specifically, a function contains a set of code that works on many kinds of inputs, like variants,
expressions and produces a concrete output.
3. Write the inference you get from X:=(78).
X:= (78) has an expression in it but (78) is not itself an expression. Rather, it is a function
definition. Definitions bind values to names, in this case the value 78 being bound to the name
‘X’.

..1..
– 1. FUNCTION
4. Differentiate interface and implementation.
Interface Implementation
Interface just defines what an object can do, Implementation carries out the instructions
but won’t actually do it. defined in the interface.
5. Which of the following is a normal function definition and which is recursive function
definition
i) let sum x y: return x + y Answers:
ii) let disp: i) Normal function
print ‘welcome’ ii) Normal Function
iii) let sum num: iii) Recursive Function
if (num!=0) then return num + sum (num-1)
else
return num
Part - III
Answer the following questions (3 Marks)
1. Mention the characteristics of Interface.
➢ The class template specifies the interfaces to enable an object to be created and operated
properly.
➢ An object's attributes and behaviour are controlled by sending functions to the object.
2. Why strlen is called pure function?
Each time you call the strlen() function with the same parameters, it always gives the same
correct answer. So, it is a pure function.
3. What is the side effect of impure function. Give example.
When a function depends on variables or functions outside of its definition block, you can
never be sure that the function will behave the same every time it’s called.
Example: random() function
4. Differentiate pure and impure function.
Pure Function Impure Function

The return value of the pure functions solely The return value of the impure functions
depends on its arguments passed. does not solely depend on its arguments
passed.

Hence, if you call the pure functions with the Hence, if you call the impure functions with
same set of arguments, you will always get the same set of arguments, you might get
the same return values. the different return values.
They do not have any side effects. They have side effects.

They do not modify the arguments which They may modify the arguments which are
are passed to them. passed to them.

..2..
– 1. FUNCTION
5. What happens if you modify a variable outside the function? Give an example.
One of the most popular side effects is modifying the variable outside of function.
For example
y: = 0
let inc (x:int): int:=
y: = y + x;
return (y)
In the above example the value of ‘y’ get changed inside the function definition due to
which the result will change each time. The side effect of the inc() function is it is changing
the data of the external visible variable ‘y’.
Part - IV
Answer the following questions (5 Marks)
1. What are called Parameters and write a note on
(i) Parameter without Type
(ii) Parameter with Type
Parameters are the variables in a function definition and arguments are the values which
are passed to a function definition.
(i) Parameter without Type:
❖ In the above function definition, the variables 'a' and
let rec pow a b:= 'b' are parameters and the value which is passed to the
if b=0 then 1 variables 'a' and 'b' are arguments. We have also not
else a * pow a (b-1) specified the datatype for 'a' and 'b'. This is an example
of parameters without type.
❖ Some language compiler solves this type (data type) inference problem algorithmically,
but some require the type to be mentioned.
(ii) Parameter with Type:
❖ The parameters 'a' and 'b' are specified in the
data type brackets () in the above function
let rec pow (a: int) (b: int) : int := definition.
if b=0 then 1 ❖ This is useful on times when you get a type
else a * pow a (b-1) error from the compiler that doesn't make
sense. Explicitly annotating the types can help
with debugging such an error message.
2. Identify in the following program
let rec gcd a b :=
if b <> 0 then gcd b (a mod b) else return a
i) Name of the function
ii) Identify the statement which tells it is a recursive function
iii) Name of the argument variable
iv) Statement which invoke the function recursively
v) Statement which terminates the recursion
..3..
– 1. FUNCTION
Answers:
i) gcd
ii) let rec gcd a b
iii) a, b
iv) if b <> 0 then gcd b (a mod b)
v) return a
3. Explain with example Pure and impure functions.
Pure function:
❖ The return value of the pure functions solely depends on its arguments passed. Hence, if
you call the pure functions with the same set of arguments, you will always get the same
return values.
❖ They do not have any side effects.
Example:
strlen() function always gives the same correct answer every time you call with the same
parameters. So it is a pure function.
Impure function:
❖ The return value of the impure functions does not solely depend on its arguments passed.
Hence, if you call the impure functions with the same set of arguments, you might get the
different return values.
❖ They have side effects.
For example, the mathematical function random() will give different outputs for the same
function call.
4. Explain with an example interface and implementation.
Interface:
An interface is a set of action that an object can do. Interface just defines what an object
can do, but won’t actually do it.
Implementation:
Implementation carries out the instructions defined in the interface.
For example, let's take the example of increasing a car’s speed.

ENGINE

getSpeed

No
Requi
red
Pull Fuel
Spe
Yes
Return

..4..
– 1. FUNCTION
➢ The person who drives the car doesn't care about the internal working.
➢ To increase the speed of the car he just presses the accelerator to get the desired
behaviour. Here the accelerator is the interface between the driver (the calling / invoking
object) and the engine (the called object).
➢ Internally, the engine of the car is doing all the things. It's where fuel, air, pressure, and
electricity come together to create the power to move the vehicle.
➢ All of these actions are separated from the driver, who just wants to go faster. Thus, we
separate interface from implementation.
ADDITIONAL QUESTIONS
1. The syntax to define function begins with
a) fun b) func c) let d) rec
2. Which of the following key indicate that the function is a recursive function?
a) rec b) recursive c) recur d) recu
3. All functions are ______ definitions.
a) static b) data type c) dynamic d) return
4. A function definition which calls itself is called
a) main function b) self-function
c) function definition d) recursive function
5. Which of the following do not have any side effects?
a) User defined functions b) Pure functions
c) Impure functions d) Assigned functions
6. Which of the following function is a impure function?
(a) strlen() (b) sin() (c) random() (d) gcd()
7. An instance created for the class is
a) Function b) Variables c) Objects d) Constructors
8. What are parameters and arguments?
❖ Parameters are the variables in a function definition.
❖ Arguments are the values which are passed to a function definition.
9. What is recursive function?
A function definition which calls itself is called recursive function.
10. `How will you solve the problem of chameleons in chrome land? Describe by
algorithm and flowchart?
➢ If the two types of chameleons are an equal number, then these two types together will
change to the color of the third type. In the end, all should display the same color.
➢ Let us represent the number of chameleons of each type by variables a, b and c, and their
initial values by A, B and C, respectively.
➢ Let a = b be the input property. The input – output relation is a = b = 0 and c = A + B + C.
➢ Let us name the algorithm monochromatize. The algorithm can be specified as
monochromatize (a, b, c)
inputs: a = A, b = B, c = C, a = b
outputs: a = b = 0, c = A+B+C
..5..
2 DATA ABSTRACTION

Part - I
Choose the best answer: (1 Mark)
1. Which of the following functions that build the abstract data type?
(A) Constructors (B) Destructors (C) recursive (D) Nested
2. Which of the following functions that retrieve information from the data type?
(A) Constructors (B) Selectors (C) recursive (D) Nested
3. The data structure which is a mutable ordered sequence of elements is called
(A) Built in (B) List (C) Tuple (D) Derived data
4. A sequence of immutable objects is called
(A) Built in (B) List (C) Tuple (D) Derived data
5. The data type whose representation is known are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
6. The data type whose representation is unknown are called
(A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
7. Which of the following is a compound structure?
(A) Pair (B) Triplet (C) single (D) quadrat
8. Bundling two values together into one can be considered as
(A) Pair (B) Triplet (C) single (D) quadrat
9. Which of the following allow to name the various parts of a multi-item object?
(A) Tuples (B) Lists (C) Classes (D) quadrats
10. Which of the following is constructed by placing expressions within square brackets?
(A) Tuples (B) Lists (C) Classes (D) quadrats
Part - II
Answer the following questions: (2 Marks)
1. What is abstract data type?
Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set
of value and a set of operations.
2. Differentiate constructors and selectors.
➢ Constructors are functions that build the abstract data type.
➢ Selectors are functions that retrieve information from the data type.
3. What is a Pair? Give an example.
➢ Any way of bundling two values together into one can be considered as a pair.
➢ Pair is a compound structure which is made up of list or Tuple.
Example: lst := [5, 10, 20]
4. What is a List? Give an example.
➢ List is constructed by placing expressions within square brackets separated by commas.
Such an expression is called a list literal.

..7..
– 2. DATA ABSTRACTION
➢ List can store multiple values. Each value can be of any type and can even be another
list.
Example: lst := [10, 20]
5. What is a Tuple? Give an example.
A tuple is a comma-separated sequence of values surrounded with parentheses. The
elements given in the tuple cannot be changed.
Example: t := (10, 12)
Part - III
Answer the following questions: (3 Marks)
1. Differentiate Concrete data type and abstract datatype.
Concrete data type Abstract datatype
Concrete data types or structures (CDT's) Abstract Data Types (ADT's) offer a high
are direct implementations of a relatively level view (and use) of a concept
simple concept. independent of its implementation.
2. Which strategy is used for program designing? Define that Strategy.
➢ The strategy followed in program design is Wishful Thinking.
➢ Wishful Thinking is the formation of beliefs and making decisions according to what
might be pleasing to imagine instead of by appealing to reality.
3. Identify Which of the following are constructors and selectors?
(a) N1=number( ) - Constructor
(b) accetnum(n1) - Selectors
(c) displaynum(n1) - Selectors
(d) eval(a/b) - Selectors
(e) x,y= makeslope (m), makeslope(n) - Constructor
(f) display( ) - Selectors
4. What are the different ways to access the elements of a list. Give example.
The elements of the list can be accessed in two ways.
1] Multiple assignment:
In this method, which unpacks a list into its elements and binds each element to a
different name.
Example: Ist := [10, 20]
x, y := lst
2] Element selection operator:
The value within the square brackets selects an element from the value of the preceding
expression.
Example:
lst = [10,20]
lst[0]
10
lst[1]
20

..8..
– 2. DATA ABSTRACTION
5. Identify Which of the following are List, Tuple and class ?
(a) arr [1, 2, 34] - List
(b) arr (1, 2, 34) - Tuple
(c) student [rno, name, mark] - Class
(d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’) - Tuple
(e) x= [2, 5, 6.5, [5, 6], 8.2] - List
(f) employee [eno, ename, esal, eaddress] - Class
Part - IV
Answer the following questions: (5 Marks)
1. How will you facilitate data abstraction. Explain it with suitable example.
To facilitate data abstraction, you will need to create constructors and selectors.
➢ Constructors are functions that build the abstract data type.
➢ Selectors are functions that retrieve information from the data type.
for example
Let's take an abstract datatype called city. This city object will hold the city's name, and its
latitude and longitude.
city = makecity (name, lat, lon)
✓ Here the function makecity (name, lat, lon) is the constructor. When it creates an
object city, the values name, lat and lon are sent as parameters.
✓ getname(city), getlat(city) and getlon(city) are selector functions that obtain
information from the object city.
2. What is a List? Why List can be called as Pairs. Explain with suitable example
➢ List is constructed by placing expressions within square brackets separated by commas.
Such an expression is called a list literal.
➢ List can store multiple values. Each value can be of any type and can even be another list.
Example:
lst := [10, 20]
The above example mathematically we can represent.
lst[(0, 10), (1, 20)]
where 0 and 1 are index position and 10 and 20 are values.
➢ Any way of bundling two values together into one can be considered as a pair. Lists are a
common method to do so. Therefore, List can be called as Pairs.
3. How will you access the multi-item. Explain with example.
You can use the structure construct in the OOP language to represent multi-part objects
where each part is named. Consider the following pseudo code:
class Person:
creation( )
firstName := " "
lastName := " "
id := " "
email := " "
..9..
– 2. DATA ABSTRACTION
✓ The new data type Person is the class name, creation() is the function and firstName,
lastName, id, email are class variables.
✓ The object p1 is created in the p1 := person( ) statement and p1.firstName,
p1.lastName, p1.id and p1.email can be accessed from the object p1.
ADDITIONAL QUESTIONS
1. _______ provides modularity.
a) Abstraction b) Constructor c) Recursion d) Structures
2. Splitting a program into many modules is called
a) Control Flow b) Looping c) Abstraction d) Modularity
3. Which of the following are the representation for “Abstract Data Types”?
a) Object b) Classes c) Functions d) Inheritance
4. Which of the following is a compound structure?
a) Pairs b) Triplet c) Single d) Quadrat
5. How many ways are used to access the list element?
a) 3 b) 2 c) 5 d) 4
6. The expansion of ADT is
a) Built-in datatype b) Derived datatype
c) Concrete datatype d) Abstract Data Type
7. The expansion of CDT is
a) Built-in datatype b) Derived datatype
c) Concrete Data Type d) Abstract Data Type
8. To facilitate data abstraction, you will need to create ______ types of functions.
a) 3 b) 2 c) 5 d) 4
9. Which of the following creates List expressions?
a) ( ) b) [ ] c) < > d) { }
10. Which of the following constructs Tuples expressions?
a) ( ) b) [ ] c) < > d) { }
11. We are using here a powerful strategy for designing programs:
a) Abstraction b) Wishful thinking c) Constructors d) Pairs
12. List is constructed by placing expressions within square brackets separated by
a) Periods(.) b) Colon(:) c) Semicolon(;) d) Comma(,)
13. dentify the correct list usage from the following:
i. LIST[10,20] ii. LIST(10,20) iii. LIST[(0,10),(1,20)] iv. LIST{10,20}
a) i Only b) i, ii Only c) i, iii Only d) i, ii, iii, iv
14. Which of the following is used to represent multi-part objects where each part is named?
a) Class b) Function c) Structure d) Object
15. What is abstraction?
The process of providing only the essentials and hiding the details is known as abstraction.
16. Explain the representation of Abstract datatype using Rational numbers.
➢ The basic idea of data abstraction is to structure programs so that they operate on
abstract data.

..10..
3 SCOPING

Part - I
Choose the best answer: (1 Mark)
1. Which of the following refers to the visibility of variables in one part of a program to
another part of the same program.
(A) Scope (B) Memory (C) Address (D) Accessibility
2. The process of binding a variable name with an object is called
(A) Scope (B) Mapping (C) late binding (D) early binding
3. Which of the following is used in programming languages to map the variable and object?
(A) :: (B) := (C) = (D) ==
4. Containers for mapping names of variables to objects is called
(A) Scope (B) Mapping (C) Binding (D) Namespaces
5. Which scope refers to variables defined in current function?
(A) Local Scope (B) Global scope
(C) Module scope (D) Function Scope
6. The process of subdividing a computer program into separate sub-programs is called
(A) Procedural Programming (B) Modular programming
(C) Event Driven Programming (D) Object oriented Programming
7. Which of the following security technique that regulates who can use resources in a
computing environment?
(A) Password (B) Authentication (C) Access control (D) Certification
8. Which of the following members of a class can be handled only from within the class?
(A) Public members (B) Protected members
(C) Secured members (D) Private members
9. Which members are accessible from outside the class?
(A) Public members (B) Protected members
(C) Secured members (D) Private members
10. The members that are accessible from within the class and are also available to its
subclasses is called
(A) Public members (B) Protected members
(C) Secured members (D) Private members
Part - II
Answer the following questions: (2 Marks)
1. What is a scope?
Scope refers to the accessibility of a variable with in one part of a program to another
part of the same program.
2. Why scope should be used for variable. State the reason.
➢ The definition is used to indicate which part of the program the variable can be accessed
or used.

..12..
– 3. SCOPING
➢ It is a good practice to limit a variable's scope to a single definition. This way, changes
inside the function can't affect the variable on the outside of the function in unexpected
ways.
3. What is Mapping?
The process of binding a variable name with an object is called mapping. = (equal to sign)
is used in programming languages to map the variable and object.
4. What do you mean by Namespaces?
Namespaces are containers for mapping names of variables to objects.
5. How Python represents the private and protected Access specifiers?
➢ Python prescribes a convention of prefixing the name of the variable or method with
single or double underscore to emulate the behaviour of protected and private access
specifiers.
➢ All members in a Python class are public by default.
Part - III
Answer the following questions: (3 Marks)
1. Define Local scope with an example.
➢ Local scope refers to variables defined in current function.
➢ Always, a function will first look up for a variable name in its local scope. Only if it does
not find it there, the outer scopes are checked.
Example: Output:
Disp( ): 7
a := 7 → local scope
print a
Disp( )
2. Define Global scope with an example.
➢ A variable which is declared outside of all the functions in a program is known as global
variable.
➢ This means, global variable can be accessed inside or outside of all the functions in a
program.
Example: Output:
a := 10 → global scope 7
Disp( ): 10
a := 7 → local scope
print a
Disp()
print a
3. Define Enclosed scope with an example.
➢ A function (method) with in another function is called nested function.
➢ A variable which is declared inside a function which contains another function definition
with in it, the inner function can also access the variable of the outer function. This scope
is called enclosed scope.
..13..
– 3. SCOPING
Example: Output:
Disp(): 10
a := 10 → enclosed scope 10
Disp1()
print a
Disp1()
print a
4. Why access control is required?
Access control is a security technique that regulates who or what can view or use
resources in a computing environment. It is a fundamental concept in security that
minimizes risk to the object.
5. Identify the scope of the variables in the following pseudo code and write its output.
color:= Red Scope of variables:
mycolor(): color → global scope
b:=Blue b → enclosed scope
myfavcolor(): g → local scope
g:=Green Output:
print color, b, g Red Blue Green
myfavcolor() Red Blue
print color, b Red
mycolor()
print color
Part - IV
Answer the following questions: (5 Marks)
1. Explain the types of scopes for variable or LEGB rule with example.
The LEGB rule is used to decide the order in which the scopes are to be searched for
scope resolution.

BUILT-IN
GLOBAL
ENCLOSED
LOCAL

Local scope:
➢ Local scope refers to variables defined in current function.
➢ Always, a function will first look up for a variable name in its local scope. Only if it does
not find it there, the outer scopes are checked.

..14..
– 3. SCOPING
Enclosed scope:
➢ A function (method) with in another function is called nested function.
➢ A variable which is declared inside a function which contains another function definition
with in it, the inner function can also access the variable of the outer function. This scope
is called enclosed scope.
Global scope:
➢ A variable which is declared outside of all the functions in a program is known as global
variable.
➢ This means, global variable can be accessed inside or outside of all the functions in a
program.
Built-in scope:
➢ The built-in scope has all the names that are pre-loaded into the program scope when we
start the compiler or interpreter.
➢ Any variable or module which is defined in the library functions of a programming
language has Built-in or module scope.
Example:
Built-in/module scope → library files
a := 10 → global scope
Disp():
b := 7 → enclosed scope
Disp1()
c := 5 → local scope
print a, b, c
Disp1()
Disp()
Output:
10
7
5
2. Write any Five Characteristics of Modules.
1. Modules contain instructions, processing logic, and data.
2. Modules can be separately compiled and stored in a library.
3. Modules can be included in a program.
4. Module segments can be used by invoking a name and some parameters.
5. Module segments can be used by other modules.
3. Write any five benefits in using modular programming.
❖ Less code to be written.
❖ Programs can be designed more easily because a small team deals with only a small part
of the entire code.
❖ Code is short, simple and easy to understand.
❖ Errors can easily be identified, as they are localized to a subroutine or function.
..15..
– 3. SCOPING
❖ The same code can be used in many applications.
❖ Modular programming allows many programmers to collaborate on the same application.
❖ The scoping of variables can easily be controlled.
ADDITIONAL QUESTIONS
1. The duration for which a variable is alive is called its
a) Scope time b) end time c) life time d) variable time
2. Scope refers to the visibility of
a) variables b) parameters c) functions d) all of these
3. Which are composed of one or more independently developed modules?
a) Access control b) Encapsulation c) Programs d) Data types
4. It is a fundamental concept in security that minimizes risk to the object.
a) Access control b) Encapsulation c) Inheritance d) Data types
5. In terms of hierarchy, the scope with highest priority is
a) Local b) Enclosed c) Global d) Built-in
6. In terms of hierarchy, the scope with lowest priority is
a) Local b) Enclosed c) Global d) Built-in
7. Always, a function will first look up for a variable name in its
a) local scope b) Enclosed scope c) Global scope d) Built-in scope
8. Which contain instructions, processing logic, and data?
a) Scope b) Object c) Modules d) Interface
9. Which of the following can be separately compiled and stored in a library?
a) Programs b) Scope c) Namespace d) Modules
10. Which of the following members of a class are denied access from the outside of class?
a) private b) public c) protected d) All of these
11. The members that are accessible from outside the class is
a) private b) public c) protected d) All of these
12. The arrangement of private instance variables and public methods ensures the principle of
a) Data Encapsulation b) Inheritance c) Polymorphism d) All of these
13. The members accessible from within the class and are also available to its sub-classes is
a) private b) public c) protected d) All of these
14. The symbol prefixed with the variable to indicate protected and private access specifiers is
a) Single underscore b) Double underscore
c) Single or Double underscore d) Backslash
15. By default, all members in a python class are
a) private b) public c) protected d) All of these
16. By default, all members in C++ and Java class are
a) private b) public c) protected d) All of these
17. What is the lifetime of a variable?
The duration for which a variable is alive is called its ‘life time’.
18. Define module.
➢ A module is a part of a program.
..16..
– 3. SCOPING
➢ Programs are composed of one or more independently developed modules.
➢ A single module can contain one or several statements closely related each other.
19. What is modular programming?
The process of subdividing a computer program into separate sub-programs is called
Modular programming.
20. What is nested function?
A function (method) with in another function is called nested function.
21. Write about the access specifiers.
➢ Public members (generally methods declared in a class) are accessible from outside the
class.
➢ Protected members of a class are accessible from within the class and are also available
to its sub-classes.
➢ Private members of a class are denied access from the outside the class. They can be
handled only from within the class.

..17..
4 ALGORITHMIC STRATEGIES

Part - I
Choose the best answer: (1 Mark)
1. The word comes from the name of a Persian mathematician Abu Ja’far Mohammed ibn-i Musa
al Khowarizmi is called?
(A) Flowchart (B) Flow (C) Algorithm (D) Syntax
2. From the following sorting algorithms which algorithm needs the minimum number of swaps?
(A) Bubble sort (B) Quick sort
(C) Merge sort (D) Selection sort
3. Two main measures for the efficiency of an algorithm are
(A) Processor and memory (B) Complexity and capacity
(C) Time and space (D) Data and space
4. The algorithm that yields expected output for a valid input is called as
(A) Algorithmic solution (B) Algorithmic outcomes
(C) Algorithmic problem (D) Algorithmic coding
5. Which of the following is used to describe the worst case of an algorithm?
(A) Big A (B) Big S (C) Big W (D) Big O
6. Big  is the reverse of
(A) Big O (B) Big  (C) Big A (D) Big S
7. Binary search is also called as
(A) Linear search (B) Sequential search
(C) Random search (D) Half-interval search
8. The Θ notation in asymptotic evaluation represents
(A) Base case (B) Average case (C) Worst case (D) NULL case
9. If a problem can be broken into subproblems which are reused several times, the problem
possesses which property?
(A) Overlapping subproblems (B) Optimal substructure
(C) Memoization (D) Greedy
10. In dynamic programming, the technique of storing the previously calculated values is called?
(A) Saving value property (B) Storing value property
(C) Memoization (D) Mapping
Part - II
Answer the following questions: (2 Marks)
1. What is an Algorithm?
An algorithm is a finite set of instructions to accomplish a particular task.
2. Write the phase of the performance evaluation of an algorithm.
1. A Priori estimates
2. A Posteriori testing
3. What is Insertion sort?
Insertion sort is a simple sorting algorithm that builds the final sorted array or list one item
at a time. It always maintains a sorted sub list in the lower positions of the list.

..18..
– 4. ALGORITHMIC STRATEGIES
4. What is Sorting?
The process of arranging the list items in ascending or descending order is called sorting.
Example:
❖ Bubble Sorting ❖ Selection sorting ❖ Insertion Sorting
5. What is searching? Write its types.
Searching is the process of finding a particular value from the list. Linear search and Binary
search are the two different types.
Part - III
Answer the following questions: (3 Marks)
1. List the characteristics of an algorithm.
i) Input ii) Output iii) Finiteness iv) Definiteness
v) Effectiveness vi) Correctness vii) Simplicity viii) Unambiguous
ix) Feasibility x) Portable xi) Independent
2. Discuss about Algorithmic complexity and its types.
Computer resources are limited. Efficiency of an algorithm is defined by the utilization of
time and space complexity.
➢ Time Complexity:
The Time complexity of an algorithm is given by the number of steps taken by the
algorithm to complete the process.
➢ Space Complexity:
Space complexity of an algorithm is the amount of memory required to run to its
completion.
3. What are the factors that influence time and space complexity.
The efficiency of an algorithm depends on how efficiently it uses time and memory space.
The time efficiency of an algorithm is measured by different factors.
✓ Speed of the machine
✓ Compiler and other system Software tools
✓ Operating System
✓ Programming language used
✓ Volume of data required
4. Write a note on Asymptotic notation.
Asymptotic Notations are languages that uses meaningful statements about time and
space complexity. The following three asymptotic notations are mostly used to represent time
complexity of algorithms:
(i) Big O → worst-case
(ii) Big Ω → best-case
(iii) Big  → average-case
5. What do you understand by Dynamic programming?
Dynamic programming is an algorithmic design method that can be used when the solution
to a problem can be viewed as the result of a sequence of decisions.

..19..
– 4. ALGORITHMIC STRATEGIES
Steps to do Dynamic programming:
➢ The given problem will be divided into smaller overlapping sub-problems.
➢ An optimum solution for the given problem can be achieved by using result of smaller
sub-problem.
➢ Dynamic algorithms use Memoization.
Part - IV
Answer the following questions: (5 Marks)
1. Explain the characteristics of an algorithm.
❖ Input: Zero or more quantities to be supplied.
❖ Output: At least one quantity is produced.
❖ Finiteness: Algorithms must terminate after finite number of steps.
❖ Definiteness: All operations should be well defined. For example, operations involving
division by zero or taking square root for negative number are unacceptable.
❖ Effectiveness: Every instruction must be carried out effectively.
❖ Correctness: The algorithms should be error free.
❖ Simplicity: Easy to implement.
❖ Unambiguous: Algorithm should be clear and unambiguous. Each of its steps and their
inputs/outputs should be clear and must lead to only one meaning.
❖ Feasibility: Should be feasible with the available resources.
❖ Portable: An algorithm should be generic, independent of any programming language or
an operating system able to handle all range of inputs.
❖ Independent: An algorithm should have step-by-step directions, which should be
independent of any programming code.
2. Discuss about Linear search algorithm.
Linear search also called sequential search. This method checks the search element with
each element in sequence until the desired element is found or the list is exhausted. In this
searching algorithm, list need not be ordered.
Pseudo code:
1. Traverse the array using for loop
2. In every iteration, compare the target search key value with the current value of the
list.
✓ If the values match, display the current index and value of the array.
✓ If the values do not match, move on to the next array element.
3. If no match is found, display the search element not found.
For example, consider the following array
a[] = {10, 12, 20, 25, 30} will be as follows,
a
Index 0 1 2 3 4
Values 10 12 20 25 30
If you search for the number 25, the index will return to 3. If the searchable number is not
in the array, for example, if you search for the number 70, it will return -1.

..20..
– 4. ALGORITHMIC STRATEGIES
3. What is Binary search? Discuss with example.
❖ Binary search also called half-interval search algorithm.
❖ It finds the position of a search element within a sorted array.
❖ The binary search algorithm can be done as divide-and-conquer search algorithm and
executes in logarithmic time.
Pseudo code for Binary search
1. Start with the middle element:
✓ If the search element is equal to the middle element of the array, then return the
index of the middle element.
✓ If not, then compare the middle element with the search value.
✓ If the search element is greater than the number in the middle index, then select the
elements to the right side of the middle index, and go to Step-1.
✓ If the search element is less than the number in the middle index, then select the
elements to the left side of the middle index, and start with Step-1.
2. When a match is found, display success message with the index of the element matched.
3. If no match is found for all comparisons, then display unsuccessful message.
For example:
Using binary search, let's assume that we are searching for the location or index of value 60.

❖ find index of middle element, use mid=low+(high-low)/2


low = 0, high = 9
mid = 0+(9-0)/2 = 4

❖ The mid value 50 is smaller than the target value 60. We have to change the value of low
to mid + 1 and find the new mid value again.
low = 5, high = 9
mid = 5 + ( 9 – 5 ) / 2 = 7

❖ The mid value 80 is greater than the target value 60. We have to change the value of high
to mid - 1 and find the new mid value again.
low = 5, high = 6
mid = 5 + ( 6 – 5 ) / 2 = 5

❖ Now we compare the value stored at location 5 with our search element. We found that
it is a match.
❖ We can conclude that the search element 60 is found at location or index 5.
..21..
– 4. ALGORITHMIC STRATEGIES
4. Explain the Bubble sort algorithm with example.
➢ Bubble sort is a simple, it is too slow and less efficient when compared to insertion sort
and other sorting methods.
➢ The algorithm starts at the beginning of the list of values stored in an array. It compares
each pair of adjacent elements and swaps them if they are in the unsorted order.
➢ This comparison and passed to be continued until no swaps are needed.
Let's consider an array with values {15, 11, 16, 12, 14, 13} Below, we have a pictorial
representation of how bubble sort will sort the given array.

The above pictorial example is for iteration-1. Similarly, remaining iteration can be done.
At the end of all the iterations we will get the sorted values in an array as given below:

5. Explain the concept of Dynamic programming with suitable example.


❖ Dynamic programming algorithm can be used when the solution to a problem can be
viewed as the result of a sequence of decisions.
❖ Dynamic programming approach is similar to divide and conquer. The given problem is
divided into smaller and yet smaller possible sub-problems.
❖ It is used whenever problems can be divided into similar sub-problems. so that their
results can be re-used to complete the process.
❖ For every inner sub problem, dynamic algorithm will try to check the results of the
previously solved sub-problems. The solutions of overlapped sub-problems are combined
in order to get the better solution.
Steps to do Dynamic programming
➢ The given problem will be divided into smaller overlapping sub-problems.
➢ An optimum solution for the given problem can be achieved by using result of smaller
sub-problem.
..22..
– 4. ALGORITHMIC STRATEGIES
➢ Dynamic algorithms uses Memoization.
Fibonacci Series – An example
Fibonacci series generates the subsequent number by adding two previous numbers.
Fibonacci Iterative Algorithm with Dynamic programming approach
Step - 1: Print the initial values of Fibonacci f0 and f1
Step - 2: Calculate fib = f0 + f1
Step - 3: Print the value of fib
Step - 4: Assign f0 = f1, f1 = fib
Step - 5: Goto Step - 2 and repeat until the specified number of terms generated.
If the number of terms is 10 then the output of the Fibonacci series is :
0 1 1 2 3 5 8 13 21 34 55
ADDITIONAL QUESTIONS
1. A finite set of instructions to accomplish a particular task is called
a) Flow chart b) Algorithm c) Pseudo code d) Walkthrough
2. The way of defining an algorithm is called
a) Algorithmic procedure b) Algorithmic definition
c) Algorithmic function d) Algorithmic strategy
3. An algorithm that yields expected output for a valid input is called
a) Problem solving b) Derivations
c) Algorithmic solution d) None of the above
4. The efficiency of which state can be expressed as O(n)?
(a) Average case (b) Best case (c) Worst case (d) NULL case
5. The efficiency of which state can be expressed as O(1)?
(a) Average case (b) Best case (c) Worst case (d) NULL case
6. Linear search is also called as
a) Continuous search b) Ordered search
c) Binary search d) Sequential search
7. Half – interval search algorithm is also called as
a) Linear search b) Binary search
c) Continuous search d) Ordered search
8. The algorithm uses ‘Divide and Conquer’ technique is
a) Insertion sort b) Bubble sort
c) Linear search d) Binary search
9. What is an algorithmic solution?
An algorithm that yields expected output for a valid input is called an algorithmic solution.
10. What is analysis if algorithm?
An estimation of the time and space complexities of an algorithm for varying input sizes
is called algorithm analysis.
11. What is algorithmic strategy?
A way of designing algorithm is called algorithmic strategy.

..23..
– 4. ALGORITHMIC STRATEGIES
12. What is time complexity?
The Time complexity of an algorithm is given by the number of steps taken by the
algorithm to complete the process.
13. What is space complexity?
Space complexity of an algorithm is the amount of memory required to run to its
completion.
14. What do you mean by best algorithm?
The best algorithm to solve a given problem is one that requires less space in memory
and takes less time to execute its instructions to generate output.
15. What is memoization?
Memoization is an optimization technique used primarily to speed up computer programs
by storing the results of expensive function calls and returning the cached result when the
same inputs occur again.
16. Differentiate between algorithm and program.
Algorithm Program
Algorithm helps to solve a given problem Program is an expression of algorithm in a
logically and it can be contrasted with the programming language.
program.
Algorithm can be categorized based on Algorithm can be implemented by
their implementation methods, design structured or object-oriented programming
techniques etc. approach.
There is no specific rules for algorithm Program should be written for the selected
writing but some guidelines should be language with specific syntax.
followed.
Algorithm resembles a pseudo code which Program is more specific to a programming
can be implemented in any language. language.

..24..
5 PYTHON – VARIABLES AND OPERATORS

Part - I
Choose the best answer: (1 Mark)
1. Who developed Python?
A) Ritche B) Guido Van Rossum
C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept instruction.
A) >>> B) <<< C) # D) <<
3. Which of the following shortcut is used to create new Python Program?
A) Ctrl + C B) Ctrl + F C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($) C) comma(,) D) Colon(:)
6. Which of the following is not a token?
A) Interpreter B) Identifiers C) Keyword D) Operators
7. Which of the following is not a Keyword in Python?
A) break B) while C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or C) not D) Assignment
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational C) Logical D) Assignment
Part - II
Answer the following questions: (2 Marks)
1. What are the different modes that can be used to test Python Program ?
Interactive mode and Script mode are the two modes that can be used to test python
program.
2. Write short notes on Tokens.
Python breaks each logical line into a sequence of elementary lexical components known
as Tokens. The normal token types are
1) Identifiers 2) Keywords 3) Operators
4) Delimiters and 5) Literals
Whitespace separation is necessary between tokens.
3. What are the different operators that can be used in Python ?
❖ Arithmetic operators ❖ Relational or Comparative operators
❖ Logical operators ❖ Assignment operators ❖ Conditional Operator
4. What is a literal? Explain the types of literals ?
Literal is a raw data given to a variable or constant. In Python, there are various types of
literals. 1) Numeric 2) String 3) Boolean
..25..
– 5. VARIABLES AND OPERATORS
5. Write short notes on Exponent data?
An Exponent data contains decimal digit part, decimal point, exponent part followed by
one or more digits.
Example : 12.E04, 24.e04
Part - III
Answer the following questions: (3 Marks)
1. Write short notes on Arithmetic operator with examples.
An arithmetic operator is a mathematical operator that takes two operands and performs
a calculation on them.
Arithmetic Operators:
Examples
Operator (Operation) Result
Assume a=100 and b=10
+ (Addition) a+b 110
- (Subtraction) a-b 90
* (Multiplication) a*b 1000
/ (Division) a/b 10.0
% (Modulus) a%b 10
** (Exponent) a ** b 10000
// (Floor Division) a // b (Integer division) 3
2. What are the assignment operators that can be used in Python?
➢ In Python, = is a simple assignment operator to assign values to variable.
➢ There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are
also available.
Assignment Operators:
=, +=, -=, *=, /=, %=,**= and //=
Example:
(i) x = 10 (ii) x += 20 → x = x + 20
3. Explain Ternary operator with examples.
➢ Ternary operator is also known as conditional operator that evaluate something based on
a condition being true or false.
➢ It simply allows testing a condition in a single line replacing the multiline if-else making
the code compact.
Syntax:
Variable_Name = [on_true] if [Test expression] else [on_false]
Example:
min = 50 if 49<50 else 70
4. Write short notes on Escape sequences with examples.
➢ In Python strings, the backslash "\" is a special character, also called the "escape"
character.

..26..
– 5. VARIABLES AND OPERATORS
➢ It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline,
and "\r" is a carriage return.
Escape sequence Description Example Output
character
\\ Backslash print("\\test") \test
\’ Single-quote print("Doesn\'t") Doesn't
\” Double-quote print("\"Python\"") "Python"
\n New line print("Python\nLanguage") Python
Language
\t Tab print("Hi \t Hello") Hi Hello
5. What are string literals? Explain.
➢ In Python a string literal is a sequence of characters surrounded by quotes.
➢ Python supports single, double and triple quotes for a string.
➢ A character literal is a single character surrounded by single or double quotes. The value
with triple-quote "' '" is used to give multi-line string literal.
Example:
s = ”Python”
c = “P”
m = ‘‘‘This is a multiline string with more than one lines’’’
Part - IV
Answer the following questions: (5 Marks)
1. Describe in detail the procedure Script mode programming.
➢ Basically, a script is a text file containing the Python statements.
➢ Python Scripts are reusable code. Once the script is created, it can be executed again and
again without retyping.
➢ The Scripts are editable.
Creating and Saving Scripts in Python
1. Choose File → New File or press Ctrl + N in Python shell window that appears an untitled
blank script text editor.
2. Type the following code
a =100
b = 350
c = a+b
print ("The Sum=", c)
3. Choose File → Save or Press Ctrl + S. Now, Save As dialog box appears on the screen.
4. Type the file name in File Name box. Python files are by default saved with extension .py
Executing Python Script
1. Choose Run → Run Module or Press F5
2. If your code has any error, it will be shown in red color in the IDLE window, and Python
describes the type of error occurred.

..27..
– 5. VARIABLES AND OPERATORS
3. To correct the errors, go back to Script editor, make corrections, save the file using Ctrl +
S or File → Save and execute it again.
4. For all error free code, the output will appear in the IDLE window of Python.
2. Explain input() and print() functions with examples.
input( ) function:
In Python, input( ) function is used to accept data as input at run time.
The syntax is
Variable = input (“prompt string”)
✓ Where, prompt string is a statement or message to the user, to know what input can
be given.
Example:
>>> city=input (“Enter Your City: ”)
Enter Your City: Namakkal
✓ input() accepts all data as string or characters but not as numbers. The int( ) function
is used to convert string data as integer data explicitly.
Example:
x = int(input( “Enter a number:” ))
print() function:
In Python, the print() function is used to display result on the screen.
The syntax is
print( “String’’ )
print( variable )
print( “string”, variable )
print( “string1”, varl, “string2”’, var2)
Example:
(1) >>>print(“Welcome’’)
Welcome
(4) >>>x = 2
>>>y = 3
>>>print( “ The sum is “, x+y )
The sum is 5
✓ The print ( ) evaluates the expression before printing it on the monitor.
✓ Comma ( , ) is used as a separator in print ( ) to print more than one item.
3. Discuss in detail about Tokens in Python.
Tokens:
Python breaks each logical line into a sequence of elementary lexical components known
as Tokens. The normal token types are
1) Identifiers 2) Keywords 3) Operators
4) Delimiters and 5) Literals
Whitespace separation is necessary between tokens.

..28..
– 5. VARIABLES AND OPERATORS
1) Identifiers:
An Identifier is a name used to identify a variable, function, class, module or object.
➢ An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
➢ Identifiers may contain digits (0 .. 9)
➢ Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
➢ Identifiers must not be a python keyword.
➢ Python does not allow punctuation character such as %,$, @ etc., within identifiers.
Example : Sum, total_marks, num1
2) Keywords:
➢ Keywords are special words used by Python interpreter to recognize the structure of
program. As these words have specific meaning for interpreter, they cannot be used
for any other purpose.
Few python’s keywords are for, while, lamba, del, if, and, or,…
3) Operators:
➢ In computer programming languages operators are special symbols which represent
computations, conditional matching etc.
➢ The value of an operator used is called operands.
➢ Operators are categorized as Arithmetic, Relational, Logical, Assignment etc.
➢ Value and variables when used with operator are known as operands.
Example : +, -, *, /, <, <=, …
4) Delimiters:
➢ Delimiters are sequence of one or more characters used to specify the boundary
between separate, independent regions in plain text or other data streams.
➢ Python uses the symbols and symbol combinations as delimiters in expressions, lists,
dictionaries and strings.
➢ The following are few delimiters:
( ) [ ] { }
, : . ; ; “
5) Literals:
➢ Literal is a raw data given to a variable or constant.
➢ In Python, there are various types of literals.
1) Numeric
2) String
3) Boolean
ADDITIONAL QUESTIONS
1. The Python language was developed by Guido van Rossum of the National Research Institute
of Mathematical and Computer Science (CWI) in which country?
a) Philippines b) Saudi Arabia c) Netherland d) Australia
2. Python was released in the year
a) 1990 b) 1991 c) 1992 d) 1993
..29..
– 5. VARIABLES AND OPERATORS
3. In how many ways python programs can be written?
a) 1 b) 2 c) 3 d) 4
4. All data values in Python are
a) class b) object c) data type d) function
5. Python files are by default saved with extension
a) .pyth b) .python c) .pyt d) .py
6. Expand : IDLE
a) Integrated Device Learning Editor
b) Internal Development Loading Environment
c) Integrated Development Learning Environment
d) Internal Drive Loaded Environment
7. Which command is used to execute python script?
a) Run → Run Module b) File → Run Module
b) Shell → Run Module d) Terminal → Run Module
8. To run the Python script by pressing the key
a) F2 b) F5 c) F7 d) F10
9. input ( ) accepts all data as ________ but not as numbers.
a) digits b) strings c) character d) None
10. The function used to convert string data as integer explicitly is
a) int() b) integer() c) num() d) digit()
11. In Python which of the following is used to indicate blocks of codes for class, function or body
of the loops and block of selection command?
a) Spaces b) Tabs c) Both a) and b) d) Empty Line
12. Which separation is necessary between tokens?
a) Whitespace b) dot c) tab d) All of these
13. It is an invalid identifier.
a) 12Name b) name c) totalmark d) num
14. Which operator is called a comparative operator?
a) = b) == c) += d) //
15. Which operator is called assignment operator?
a) = b) == c) ** d) //
16. What is the output for the following code?
>>> 5 + 50 * 10
a) 550 b) 55 c) 505 d) 15
17. Octal literals are preceded with
a) 0x b) 0o c) 0h d) 0i
18. What is the output of the following code?
a =100
b=10
print(a/b)
a) 10 b) 10.0 c) 10.5 d) 3
..30..
– 5. VARIABLES AND OPERATORS
19. The output for the following line is
print(“\” Python \””)
a) Python b) ‘Python’ c) “Python” d) “’ Python”’
20. What is the output for the following code?
>>> x = 10
>>> y = 20
>>> print(“The Sum is : “,x+y)
a) 30 b) the sum is 30
c) The Sum is 30 d) The Sum is : 30
21. What is the output of the following code?
a=100
b=30
c=a//b
print(c)
a) 10 b) 10.0 c) 10.5 d) 3
22. What is the output for the following code?
>>> a=97
>>> b=35
>>> a>b or a==b
a) True b) False c) 0 d) 1
23. What is the output for the following code?
>>> a=97
>>> b=35
>>> not (a>b and a==b)
a) True b) False c) 0 d) 1
24. What is the output for the following code?
a, b = 30, 20
min = a if a < b else b
print(min)
a) 20 b) 30 c) True d) False
25. What is the output for the following code?
x = 1 + 3.14j
print(x.imag)
a) 1+3.14j b) 1 c) 3.14 d) 3.14j
26. List the key features of Python.
✓ It is a general-purpose programming language which can be used for both scientific and
non-scientific programming.
✓ It is a platform independent programming language.
✓ The programs written in Python are easily readable and understandable.
27. What is an Interactive mode Programming?
In interactive mode Python code can be directly typed and the interpreter displays the
result(s) immediately. The interactive mode can also be used as a simple calculator.

..31..
– 5. VARIABLES AND OPERATORS
28. Write a note on comments in Python?
In Python, comments begin with hash symbol (#). The lines that begins with # are
considered as comments and ignored by the Python interpreter. Comments may be single line
or no multi-lines.
Example:
# It is Single line Comment
''' It is multiline comment which contains more than one line '''
29. What are keywords? List some keywords.
Keywords are special words used by Python interpreter to recognize the structure of
program. As these words have specific meaning for interpreter, they cannot be used for any
other purpose.
Some keywords are
class return continue for del
lambda True def while if
30. What are operators and operands?
❖ In computer programming languages operators are special symbols which represent
computations, conditional matching etc.
❖ Value and variables when used with operator are known as operands.
31. Write about Relational or Comparative operators.
❖ A Relational operator is also called as Comparative operator which checks the relationship
between two operands.
❖ If the relation is true, it returns True; otherwise, it returns False.
Operators:
==, >, <, >=, <=, !=
Example:
If a=10, b=10 then
✓ a==b returns False
✓ a>b returns True
32. Write about logical operators.
In python, Logical operators are used to perform logical operations on the given relational
expressions. There are three logical operators they are and, or and not.
Example:
If a=90, b=30 then
✓ a>b or a==b returns True
✓ a>b and a==b returns False
33. What are delimiters?
Delimiters Python uses the symbols and symbol combinations as delimiters in
expressions, lists, dictionaries and strings. Following are the delimiters.
( ) [ ] { }
, : . ; ; “

..32..
– 5. VARIABLES AND OPERATORS
34. What is identifier? Write the rules using identifiers. Give example
Identifiers An Identifier is a name used to identify a variable, function, class, module or
object.
✓ An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
✓ Identifiers may contain digits (0 .. 9)
✓ Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
✓ Identifiers must not be a python keyword.
✓ Python does not allow punctuation character such as %,$, @ etc., within identifiers.
Example of valid identifiers:
Sum, totalmark, regno, num1
Example of invalid identifiers:
12Name, name$, total-mark, continue
35. Explain data types in Python.
Python has Built-in or Fundamental data types such as Number, String, Boolean, tuples,
lists, sets and dictionaries etc.
(1) Number Data type:
➢ The built-in number objects in Python supports integers, floating point numbers and
complex numbers.
➢ Integer Data can be decimal, octal or hexadecimal.
➢ Octal integer use digit 0 (Zero) followed by letter 'o' to denote octal digits and
hexadecimal integer use 0X and L to denote long integer.
➢ A floating-point data is represented by a sequence of decimal digits that includes a
decimal point.
➢ An Exponent data contains decimal digit part, decimal point, exponent part followed by
one or more digits.
➢ Complex number is made up of two floating point values, one each for the real and
imaginary parts.
Example:
102, 0o102, 0X876 34L, 156.23 and 12.E04
(2) Boolean Data type:
A Boolean data can have any of the two values: True or False.
Example :
a=True
b=False
(3) String Data type:
String data can be enclosed in single quotes or double quotes or triple quotes.
Example :
“Tech Easy”
"SRM NIGHTINGALE MHSS"

..33..
6 CONTROL STRUCTURES

Part - I
Choose the best answer: (1 Mark)
1. How many important control structures are there in Python?
A) 3 B) 4 C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control C) Structure D) Indentation
4. Which statement is generally used as a placeholder?
A) continue B) break C) pass D) goto
5. The condition in the if statement should be in the form of
A) Arithmetic or Relational expression B) Arithmetic or Logical expression
C) Relational or Logical expression D) Arithmetic
6. Which of the following is known as definite loop?
A) do..while B) while C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
if i%3 ==0:
break
print(i,end='')
i +=1
A) 12 B) 123 C) 1234 D) 124
8. What is the output of the following snippet?
T=1
while T:
print(True)
break
A) False B) True C) 0 D) 1
9. Which amongst this is not a jump statement?
A) for B) pass C) continue D) break
10. Which punctuation should be used in the blank?
if <condition>_
statements-block 1
else:
statements-block 2
A) ; B) : C) :: D) !

..34..
– 6. CONTROL STRUCTURES
Part - II
Answer the following questions: (2 Marks)
1. List the control structures in Python.
1) Sequential
2) Alternative or Branching
3) Iterative or Looping
2. Write note on break statement.
➢ When the break statement is executed, the control flow of the program comes out of the
loop and starts executing the segment of code after the loop structure.
➢ If break statement is inside a nested loop, break will terminate the innermost loop.
Syntax:
break
3. Write is the syntax of if .. else statement.
if <condition>:
statements-block 1
else:
statements-block 2
4. Define control structure.
A program statement that causes a jump of control from one part of the program to
another is called control structure or control statement.
5. Write note on range () in loop.
range() generates a list of values starting from start till stop-1.
The syntax is
range (start, stop[,step])
Where, start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.
Example:
(i) range(1, 10) → start from 1 and end at 9
(ii) range(1, 10, 2) → returns 1 3 5 7 9
Part - III
Answer the following questions: (3 Marks)
1. Write a program to display
A
AB
ABC
ABCD
ABCDE
Program :
for i in range(65, 70):
for j in range(65, i+1):
print(chr(j), end='\t')
print('\n')

..35..
– 6. CONTROL STRUCTURES
2. Write note on if .. else structure.
The if .. else statement is used to choose between two alternatives based on a condition.
Syntax: Example:
if <condition>: a = int(input("Enter any number :"))
statements-block 1 if a%2==0:
else: print (a, " is an even number")
statements-block 2 else:
print (a, " is an odd number")
Output:
1) Enter any number :56 2) Enter any number :67
56 is an even number 67 is an odd number
3. Using if.. elif.. else statement write a suitable program to display largest of 3 numbers.
Program :
a=int(input("Enter the first number:"))
b=int(input("Enter the second number:"))
c=int(input("Enter the third number:"))
if (a>b) and (a>c):
print(a, " is the largest number")
elif (b>c):
print(b, " is the largest number ")
else:
print(c, " is the largest number ")
4. Write the syntax of while loop.
while <condition>:
statements block 1
[else:
statements block2]
5. List the differences between break and continue statements.
➢ The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.
➢ Continue statement is used to skip the remaining part of a loop and start with next
iteration.
Part - IV
Answer the following questions: (5 Marks)
1. Write a detail note on for loop.
The for loop is usually known as a definite loop, because the programmer knows exactly
how many times the loop will be executed.
Syntax:
for counter_variable in sequence:
statements-block 1
[else:
statements-block 2]

..36..
– 6. CONTROL STRUCTURES
✓ The for .... in statement is a looping statement used in Python to iterate over a
sequence of objects, i.e., it goes through each item in a sequence.
✓ Here the sequence is the collection of ordered or unordered values or even a string.
✓ The control variable accesses each item of the sequence on each iteration until it
reaches the last item in the sequence.
Example: Output:
for x in (1,2,3,4,5): 12345
print(x, end=" ")
2. Write a detail note on if.. elif.. else statement with suitable example.
When we need to construct a chain of if statement(s) then ‘elif’ clause can be used instead
of ‘else’.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
✓ condition-1 is tested if it is true then statements-block1 is executed, otherwise the
control checks condition-2,
✓ if it is true statements-block2 is executed and even if it fails statements-block n
mentioned in else part is executed.
Example: Output:
a=int(input("Enter the first number: ")) Enter the first number: 7
b=int(input("Enter the second number: ")) Enter the second number: 22
c=int(input("Enter the third number: ")) Enter the third number: 15
if (a>b) and (a>c): 22 is the largest number
print(a, " is the largest number")
elif (b>c):
print(b, " is the largest number ")
else:
print(c, " is the largest number ")
3. Write a program to display all 3 digit odd numbers.
Program:
for i in range(101,1000,2):
print(i, end='\t')
4. Write a program to display multiplication table for a given number.
Program:
n = int(input("Enter a Number :"))
x = int(input("Enter number of terms :"))
for i in range(1, x+1):
print(i, " x ", n, " = ", i*n)

..37..
– 6. CONTROL STRUCTURES
ADDITIONAL QUESTIONS
1. A program statement that causes a jump of control from one part of the program to another
is called
a) statements b) Control statements c) Blocks d) Scope
2. Which of the following is not an alternative or branching statement in Python?
a) simple if b) if..else c) if..elif..else d) while
3. Which of the following terminates the loop containing it?
a) break b) continue c) pass d) jump
4. The statement which is used to skip the remaining part of the loop and start with next
iteration is
a) break b) continue c) pass d) jump
5. Which of the following is a null statement in Python?
a) break b) continue c) pass d) null
6. The statement used as a placeholder is
a) break b) continue c) pass d) null
7. What is the output for the following code?
i = 10
while (i<=15):
print(i,end=’\t’)
i+=2
a) 10 11 12 13 14 15 b) 11 13 15
c) 10 12 14 d) 10 12 14 15
8. What is the stop value for the following statement?
range(30)
a) 0 b) 1 c) 30 d) 29
9. What is the start value for the following statement?
range(20)
a) 0 b) 1 c) 20 d) 19
10. What is the output for the following code?
i = 10
while (i<=15):
print(i,end=’\t’)
i+=1
else:
print(i)
a) 10 11 12 13 14 15 16 b) 11 13 15 16
c) 10 12 14 16 d) 10 12 14 15 16
11. What is the output for the following code?
for i in range(2,10,2):
print(i,end=’ ‘)
a) 2 4 6 8 10 b) 2 4 6 8 c) 2 4 6 d) 1 2 4 6 8
..38..
– 6. CONTROL STRUCTURES
12. What is the output for the following code?
for word in "Computer Science":
if word=="e":
break
print(word, end='')
a) Computr Scinc b) Compute
c) Comput d) Computer Scinc
13. What is the output for the following code?
for word in "Computer Science":
if word=="e":
continue
print(word, end='')
a) Computr Scinc b) Compute
c) Comput d) Computer Scinc
14. What is the output for the following code?
i=1
while True:
if i%5==0:
break
print(i,end=' ')
i+=1
a) 1 2 b) 1 2 3 c) 1 2 3 4 5 d) 1 2 3 4
15. What is Sequential Statement? Give Example.
A sequential statement is composed of a sequence of statements which are executed one
after another. A code to print your name, address and phone number is an example of
sequential statement.
Example:
print ("Hello! This is Prabhakar")
print ("43, Second Lane, North Car Street, TN")
16. What is alternative or branching statement.
Based on a decision to choose one part to another part of a program. This is called an
alternative (or) branch.
17. Write short note on simple if statement.
Simple if is the simplest of all decision-making statements. Condition should be in the
form of relational or logical expression.
Syntax:
if <condition>:
statements-block1
Example: Output:
x=int (input("Enter your age :")) Enter your age :34
if x>=18: You are eligible for voting
print ("You are eligible for voting")

..39..
– 6. CONTROL STRUCTURES
18. What is Looping? Write its types.
❖ Iteration or loop are used in situation when the user needs to execute a block of code
several of times or till the condition is satisfied. A loop statement allows to execute a
statement or group of statements multiple times.
❖ Python provides two types of looping constructs: while loop and for loop
19. What is Nested loop structure?
A loop placed within another loop is called as nested loop structure.
20. What is the use of end and sep parameters in print() function?
➢ end parameter can be used when we need to give any escape sequences like ‘\t’ for tab,
‘\n’ for new line and so on.
➢ sep as parameter can be used to specify any special characters like, (comma) ; (semicolon)
as separator between values.
21. Write the importance of indentation in python.
Indentation only creates blocks and sub-blocks like how we create blocks within a set of
{} in languages like C, C++ etc.
22. Explain the Jump Statements in Python.
➢ The jump statement in Python, is used to unconditionally transfer the control from one
part of the program to another.
➢ break, continue and pass are three keywords to achieve jump statements in Python.
break:
➢ When the break statement is executed, the control flow of the program comes out of the
loop and starts executing the segment of code after the loop structure.
➢ If break statement is inside a nested loop, break will terminate the innermost loop.
Syntax:
break
Example: Output:
for word in “Government”: Gover
if word ==’n’:
break;
print(word)
continue:
continue statement is used to skip the remaining part of a loop and start with next
iteration.
Syntax:
continue
Example: Output:
for word in “Government”: Govermet
if word ==’n’:
continue;
print(word)

..40..
– 6. CONTROL STRUCTURES
pass:
✓ pass statement in Python programming is a null statement.
✓ Nothing happens when pass is executed, it results in no operation.
✓ pass statement is generally used as a placeholder.
Syntax:
pass
Example: Output:
for word in “Government”: Government
if word ==’n’:
pass;
print(word)
23. Explain While loop with example.
while loop is entry check loop. The condition is placed in the beginning of the body of the
loop. The statements in the loop will not be executed even once if the condition is false at the
time of entering the loop.
Syntax:
while <condition>:
statements block 1
[else:
statements block2]
The statements block1 is kept executed till the condition is True. If the else part is written,
it is executed when the condition is tested False.
Example:
i=10
while (i<=15):
print (i, end='\t')
i=i+1
Output:
10 11 12 13 14 15

..41..
7 PYTHON FUNCTIONS

Part - I
Choose the best answer: (1 Mark)
1. A named blocks of code that are designed to do one specific job is called as
(A) Loop (B) Branching (c) Function (D) Block
2. A Function which calls itself is called as
(A) Built-in (B) Recursion (C) Lambda (D) return
3. Which function is called anonymous un-named function
(A) Lambda (B) Recursion (C) Function (D) define
4. Which of the following keyword is used to begin the function block?
(A) define (B) for (C) finally (D) def
5. Which of the following keyword is used to exit a function block?
(A) define (B) return (C) finally (D) def
6. While defining a function which of the following symbol is used.
(A) ; (semicolon) (B) . (dot) (C) : (colon) (D) $ (dollar)
7. In which arguments the correct positional order is passed to a function?
(A) Required (B) Keyword (C) Default (D) Variable-length
8. Read the following statement and choose the correct statement(s).
(I) In Python, you don’t have to mention the specific data types while defining function.
(II) Python keywords can be used as function name.
(A) I is correct and II is wrong (B) Both are correct
(C) I is wrong and II is correct (D) Both are wrong
9. Pick the correct one to execute the given statement successfully.
if ____ :
print(x, " is a leap year")
(A) x%2=0 (B) x%4==0 (C) x/4=0 (D) x%4=0
10. Which of the following keyword is used to define the function testpython(): ?
(A) define (B) pass (C) def (D) while
Part - II
Answer the following questions: (2 Marks)
1. What is function?
Functions are named blocks of code that are designed to do specific job.
2. Write the different types of function.
(i) User-defined Functions (iii) Lambda Functions
(ii) Built-in Functions (iv) Recursion Functions
3. What are the main advantages of function?
➢ It avoids repetition and makes high degree of code reusing.
➢ It provides better modularity for your application.
4. What is meant by scope of variable? Mention its types.
Scope of variable refers to the part of the program, where it is accessible.

..42..
– 7. PYTHON FUNCTIONS
There are two types of scopes:
i) local scope and
ii) global scope.
5. Define global scope.
➢ A variable, with global scope can be used anywhere in the program.
➢ It can be created by defining a variable outside the scope of any function.
6. What is base condition in recursive function?
➢ The condition that is applied in any recursive function is known as base condition.
➢ A base condition is must in every recursive function otherwise it will continue to execute
like an infinite loop.
7. How to set the limit for recursive function? Give an example.
➢ python stops calling recursive function after 1000 calls by default.
➢ It also allows you to change the limit using
sys.setrecursionlimit (limit_value)
Part - III
Answer the following questions: (3 Marks)
1. Write the rules of local variable.
❖ A variable with local scope can be accessed only within the function that it is created in.
❖ When a variable is created inside the function the variable becomes local to it.
❖ A local variable only exists while the function is executing.
❖ The formal parameters are also local to function.
2. Write the basic rules for global keyword in python.
❖ When we define a variable outside a function, it’s global by default. You don’t have to use
global keyword.
❖ We use global keyword to modify the value of the global variable inside a function.
❖ Use of global keyword outside a function has no effect.
3. What happens when we modify global variable inside the function?
❖ When we try to modify global variable inside the function an “Unbound Local Error” will
occur.
❖ Without using the global keyword, we cannot modify the global variable inside the
function but we can only access the global variable.
4. Differentiate ceil() and floor() function?
floor(x) ceil (x)
It returns the largest integer less than or It returns the smallest integer greater than
equal to x. or equal to x.
Example: Example:
print(math.floor(2.5)) →2 :
print(math.floor(-2.5)) → -3 print(math.ceil(2.5)) →3
print(math.ceil(-2.5)) → -2

..43..
– 7. PYTHON FUNCTIONS
5. Write a Python code to check whether a given year is leap year or not.
n=int(input("Enter a Year : "))
if n%4 == 0:
print(n," is a Leap Year")
else:
print(n," is not a Leap Year")
6. What is composition in functions?
The value returned by a function may be used as an argument for another function in a
nested manner. This is called composition.
Example :
n1 = eval (input ("Enter a number: "))
✓ In the above coding eval() function takes the returned value of string-based input
from input() function.
7. How recursive function works?
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue
recursion.
8. What are the points to be noted while defining a function?
❖ Function blocks begin with the keyword “def” followed by function name and
parenthesis ().
❖ Any input parameters or arguments should be placed within these parentheses when you
define a function.
❖ The code block always comes after a colon (:) and is indented.
❖ The statement “return [expression]” exits a function, optionally passing back an
expression to the caller.
Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of function with an example.
1) User-defined Functions:
We can define our own function. These are called used defined functions. Functions
must be defined, to create and use certain functionality.
Syntax:
def <function_name ([parameter1, parameter2…] )> :
<Block of Statements>
return <expression / None>
Example: Output:
def hello(): hello – Python
print (“hello - Python”)
return
hello()
..44..
– 7. PYTHON FUNCTIONS
2) Built-in Functions:
➢ The built-in functions are pre-defined by the python interpreter.
➢ These functions perform a specific task and can be used in any program, depending on
the requirement of the user.
➢ Few functions are abs(), sqrt(),pow(), max(),…
3) Lambda or Anonymous Functions:
➢ In Python, anonymous function is a function that is defined without a name.
➢ While normal functions are defined using the def keyword, in Python anonymous
functions are defined using the lambda keyword. Hence, anonymous functions are also
called as lambda functions.
Syntax:
lambda [argument(s)] : expression
Example: Output:
sum = lambda arg1, arg2: arg1 + arg2 The Sum is : 70
print ('The Sum is :', sum(30,40))
✓ The above lambda function that adds argument arg1 with argument arg2 and stores
the result in the variable sum. The result is displayed using the print().
4) Recursion Functions:
➢ When a function calls itself is known as recursion.
Example: Output:
def fact(n): 1
if n == 0: 120
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
2. Explain the scope of variables with an example.
❖ Scope of variable refers to the part of the program, where it is accessible.
❖ local scope and global scope are two types of scopes.
Local Scope:
A variable declared inside the function's body is known as local variable.
Rules of local variable
❖ A variable with local scope can be accessed only within the function that it is created in.
❖ When a variable is created inside the function the variable becomes local to it.
❖ A local variable only exists while the function is executing.
❖ The formal parameters are also local to function.
Example: Output:
def loc(): 0
y = 0 → local scope
print(y)
loc()
..45..
– 7. PYTHON FUNCTIONS
Global Scope:
A variable, with global scope can be used anywhere in the program. It can be created by
defining a variable outside the scope of any function.
Rules of global Keyword
❖ When we define a variable outside a function, it’s global by default. You don’t have to use
global keyword.
❖ We use global keyword to modify the value of the global variable inside a function.
❖ Use of global keyword outside a function has no effect.
Example: Output:
c=1 → global variable 1
def add():
print(c)
add()
3. Explain the following built-in functions.
(a) id() :
id( ) Return the “identity” of an object. i.e. the address of the object in memory.
Syntax:
id (object)
Example: Output:
x=15 address of x is : 1357486752
print ('address of x is :',id (x))
(b) chr() :
It returns the Unicode character for the given ASCII value.
Syntax:
chr (i)
Example: Output:
c=65 A
print (chr (c))
(c) round()
It returns the nearest integer to its input. First argument (number) is used to specify
the value to be rounded. Second argument (n digits) is used to specify the number of
decimal digits desired after rounding.
Syntax:
round (number [,ndigits])
Example: Output:
n1=17.89 17.9
print (round (n1,1))
(d) type() :
It returns the type of object for the given single object.
Syntax:
type (object)
..46..
– 7. PYTHON FUNCTIONS
Example: Output:
x= 15.2 <class 'float'>
print (type (x))
(e) pow() :
It returns the computation of ab i.e. (ab ) a raised to the power of b.
Syntax:
pow (a,b)
Example: Output:
a= 5 25
b= 2
print (pow (a,b))
4. Write a Python code to find the L.C.M. of two numbers.
Program: Output:
a = int(input("Enter First Number :")) Enter First Number :5
b = int(input("Enter Second Number :")) Enter Second Number :3
if a>b: 15
min = a
else:
min = b
while 1:
if min % a ==0 and min % b ==0:
print (min)
break
min = min + 1
5. Explain recursive function with an example.
➢ When a function calls itself is known as recursion.
➢ The condition that is applied in any recursive function is known as base condition. A base
condition is must in every recursive function otherwise it will continue to execute like an
infinite loop.
Overview of how recursive function works
1) Recursive function is called by some external code.
2) If the base condition is met then the program gives meaningful output and exits.
3) Otherwise, function does some required processing and then calls itself to continue
recursion.
Example: Output:
def fact(n): 1
if n == 0: 120
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
..47..
– 7. PYTHON FUNCTIONS
➢ python stops calling recursive function after 1000 calls by default. It also allows
you to change the limit using
sys.setrecursionlimit (limit_value).
Example:
import sys
sys.setrecursionlimit(3000)
print(fact (2000))
ADDITIONAL QUESTIONS
1. It avoids repetition and makes high degree of code reusing.
a) Function b) Loop c) Branching d) Jumping
2. Basically, we can divide functions into _____ types.
a) 1 b) 2 c) 3 d) 4
3. How many types of arguments are used by functions in Python?
a) 1 b) 2 c) 3 d) 4
4. Which of the following statement indicates end of the function?
a) Function prototype b) Function name c) end d) return
5. The variables used in the function definition are called
a) Parameters b) Arguments c) Identifiers d) Constants
6. The values we pass to the function parameters are called
a) Parameters b) Arguments c) Identifiers d) Constants
7. Which of the following allows you to put arguments in improper order?
a) Keyword arguments b) Variable – length argument
c) Default argument d) Required argument
8. An argument that takes a default value if no value is provided in the function call is
a) Keyword arguments b) Variable – length argument
c) Default argument d) Required argument
9. The symbol used to define arguments in Variable – length argument is
a) # b)  c) $ d) :
10. The following code is an example for
def sample(b,c,a):
print(“Welcome”)
return
sample(a,b,c)
a) Keyword arguments b) Variable – length argument
c) Default argument d) Required argument
11. What is the output of the following code?
def loc():
y = “Local”
loc()
print(y)
a) Local b) y c) y = “Local” d) Error
..48..
– 7. PYTHON FUNCTIONS
12. What is the output of the following code?
def hello():
return
print(hello())
a) hello – Python b) Hello – Python c) None d) hello
13. What is the output of the following code:
def hello():
print(“hello – Python”)
return
print(hello())
a) hello – Python b) Hello – Python c) None d) None
None None hello – Python python
14. What is the output of the following code?
def add(a,b=3,c):
return a+b+c
print(add(5,10,15))
a) 30 b) 23 c) 10 d) Error
15. What is the output of the following code?
def add(a,b=3,c=2):
return a+b+c
print(add(5,10,15))
a) 30 b) 23 c) 10 d) Error
16. What is the output of the following code?
Sum=lambda a1,a2:a1+a2
print(Sum(20,40))
print(Sum(-20,40))
a) 60 b) 20 c) 240 d) 60
-60 -20 20 20
17. What is the output of the following code?
c=1
def add():
c=c+2
print(c)
add()
a) 1 b) 3 c) 2 d) Error
18. Default recursive calls in Python is
a) 1000 b) 2000 c) 1100 d) 2200
19. In Python, anonymous functions are defined using the keyword,
a) def b) rec c) lambda d) let
20. Which of the following keyword is necessary to modify the value of global variable inside the
function?
a) glob b) global c) glopal d) public
..49..
– 7. PYTHON FUNCTIONS
21. What is the output of the following code?
x=0
def add():
global x
x=x+5
print(x)
add()
print(x)
a) 5 b) 10
10 10
c) 5 d) Error
5
22. What is the output of the following code?
x = -18.3
print(round(x))
a) 18 b) -18 c) -18.5 d) -19
23. What is the output of the following code?
x=5
def loc():
x = 10
print(x)
loc()
print(x)
a) 5 b) 10 c) 5 d) 10
10 10 5 5
24. What is the output of the following statement?
eval(‘25*2-5*4’)
a) -300 b) 180 c) 30 c) -450
25. What is a block?
A block is one or more lines of code, grouped together so that they are treated as one big
sequence of statements while execution. In Python, statements in a block are written with
indentation.
26. What is nested block?
A block within a block is called nested block. When the first block statement is indented
by a single tab space, the second block of statement is indented by double tab spaces.
27. What are the advantages of user defined functions?
❖ Functions help us to divide a program into modules. This makes the code easier to
manage.
❖ It implements code reuse. Every time you need to execute a sequence of statements, all
you need to do is to call the function.

..50..
– 7. PYTHON FUNCTIONS
❖ Functions, allows us to change functionality easily, and different programmers can work
on different functions.
28. What are parameters and arguments?
❖ Parameters are the variables used in the function definition
❖ The values we pass to the function parameters are called arguments.
29. List the different types of arguments and explain with suitable examples.
The different function arguments are
1. Required arguments 2. Keyword arguments
3. Default arguments 4. Variable-length arguments
1. Required Arguments:
➢ Required Arguments are the arguments passed to a function in correct positional
order.
➢ Here, the number of arguments in the function call should match exactly with the
function definition. You need at least one parameter to prevent syntax errors to get
the required output.
Example:
def printstring(str):
print ("Example - Required arguments ")
print (str)
return
✓ printstring(“Welcome”)
When the above code is executed, it produces the following error.
✓ if we use printstring (“Welcome”) then the output is
Example - Required arguments
Welcome
2. Keyword Arguments:
➢ Keyword arguments will invoke the function after the parameters are recognized by
their parameter names.
➢ The value of the keyword argument is matched with the parameter name and so, one
can also put arguments in improper order (not in order).
Example:
def printdata (name, age):
print ("Example-3 Keyword arguments")
print ("Name :",name)
print ("Age :",age)
return
✓ If you call the function printdata(name="Vijay",age=25), you will get the following
output
Name : Vijay
Age :25

..51..
– 7. PYTHON FUNCTIONS
✓ If you call the function printdata (age=25,name="Vijay") by changing the order of
parameters, you will get the following output
Name :Vijay
Age :25
3. Default Arguments:
➢ In Python the default argument is an argument that takes a default value if no value
is provided in the function call.
Example:
def printinfo( name, salary = 3500):
print (“Name: “, name)
print (“Salary: “, salary)
return
printinfo(“Vijay”)
✓ When the above code is executed, it produces the following output
Name : Vijay
Salary : 3500
✓ When the above code is changed as printinfo(“Vijay”,2000) it produces the following
output:
Name: Vijay
Salary: 2000
4. Variable-Length Arguments:
➢ In some instances you might need to pass more arguments than have already been
specified. Variable-Length arguments can be used instead.
➢ An asterisk (*) is used to define such arguments.
Example:
def printnos (*nos):
for n in nos:
print(n)
return
✓ printnos(1,2) If you call the function with two parameters, you get the output as 1 2.
✓ printnos(10,20,30) If you call the function with three parameters, you will get the
output as 10 20 30.
30. Explain the return statement in detail.
❖ The return statement causes your function to exit and returns a value to its caller. The
point of functions in general is to take inputs and return something.
❖ The return statement is used when a function is ready to return a value to its caller. So,
only one return statement is executed at run time even though the function contains
multiple return statements.
❖ Any number of 'return' statements are allowed in a function definition but only one of
them is executed at run time.

..52..
– 7. PYTHON FUNCTIONS
Syntax:
return [expression list]
➢ This statement can contain expression which gets evaluated and the value is
returned.
➢ If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.
Example:
def usr_abs (n):
if n>=0:
return n
else:
return –n
x=int (input(“Enter a number :”)
print (usr_abs (x))
Output 1: Output 2:
Enter a number : 25 Enter a number : -25
25 25

..53..
8 STRINGS AND STRING MANIPULATION

Part - I
Choose the best answer: (1 Mark)
1. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(A) Tamilnadu (B) Tmlau (C) udanlimaT (D) udaNlimaT
2. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(A) Chennai-Schools (B) Chenna-School (C) Type error (D) Chennai
3. Which of the following operator is used for concatenation?
(A) + (B) & (C) * (D) =
4. Defining strings within triple quotes allows creating:
(A) Single line Strings (B) Multiline Strings
(C) Double line Strings (D) Multiple Strings
5. Strings in python:
(A) Changeable (B) Mutable (C) Immutable (D) flexible
6. Which of the following is the slicing operator?
(A) { } (B) [ ] (C) < > (D) ( )
7. What is stride?
(A) index value of slide operation (B) first argument of slice operation
(C) second argument of slice operation (D) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in upper case?
(A) %e (B) %E (C) %g (D) %n
9. Which of the following is used as placeholders or replacement fields which get replaced along
with format( ) function?
(A) { } (B) < > (C) ++ (D) ^^
10. The subscript of a string may be:
(A) Positive (B) Negative
(C) Both (A) and (B) (D) Either (A) or (B)
Part - II
Answer the following questions: (2 Marks)
1. What is String?
String is a sequence of Unicode characters that may be a combination of letters, numbers,
or special symbols enclosed within single, double or even triple quotes.
Example:
(i) ‘School’ (ii) “School” (iii) ‘‘‘School’’’
2. Do you modify a string in Python?
No. Strings are immutable in python.

..54..
– 8. STRINGS AND STRING MANIPULATION
3. How will you delete a string in Python?
Python will not allow deleting a string. Whereas you can remove entire string variable
using del command.
Example:
>>> str1="Hello"
>>> del str1
4. What will be the output of the following python code?
str1 = “School”
print(str1*3)
Output:
SchoolSchoolSchool
5. What is slicing?
Slice is a substring of a main string. A substring can be taken from the original string by
using [ ] operator and index or subscript values.
Part - III
Answer the following questions: (3 Marks)
1. Write a Python program to display the given pattern.
COMPUTER Program:
COMPUTE str="COMPUTER"
COMPUT i = len(str)
COMPU while (i > 0):
COMP print(str[:i])
COM i = i -1
CO
C
2. Write a short about the followings with suitable example:
(a) capitalize( ) (b) swapcase( )
(a) capitalize( ): (b) swapcase( )
It used to capitalize the first character It will change case of every character to
of the string. its opposite case vice-versa.
Example: Example:
>>> city="tamilnadu" >>>str1="tamil NADU"
>>> print(city.capitalize()) >>> print(str1.swapcase())
Tamilnadu TAMIL nadu
3. What will be the output of the given python program?
str1 = "welcome"
str2 = "to school"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
Output:
weol
..55..
– 8. STRINGS AND STRING MANIPULATION
4. What is the use of format()? Give an example.
❖ The format() function used with strings is very versatile and powerful function used for
formatting strings.
❖ The curly braces {} are used as placeholders or replacement fields which get replaced
along with format() function.
Example: Output:
a=2 The product of 2 and 4 is 8
b=4
print(“The product of {} and {} is {}”, format(a, b, ab))
5. Write a note about count() function in python.
❖ count() function returns the number of substrings occurs within the given range.
Remember that substring may be a single character.
❖ Range (beg and end) arguments are optional. If it is not given, python searched in whole
string. Search is case sensitive.
Syntax:
count(str[,beg, end])
Example:
>>>str1="Raja Raja Chozhan"
>>>print(str1.count('Raja'))
2
>>>print(str1.count('a'))
5
Part - IV
Answer the following questions: (5 Marks)
1. Explain about string operators in python with suitable example.
(i) Concatenation (+):
Joining of two or more strings is called as Concatenation. The plus (+) operator is used
to concatenate strings in python.
Example:
>>> "welcome to " + "Python"
welcome to Python
(ii) Append (+=):
Adding more strings at the end of an existing string is known as append. The operator
+= is used to append a new string with an existing string.
Example:
>>> str1="Welcome to "
>>> str1+="Learn Python"
>>> print (str1)
Welcome to Learn Python
(iii) Repeating ():
The multiplication operator () is used to display a string in multiple number of times.

..56..
– 8. STRINGS AND STRING MANIPULATION
Example:
>>> str1="Welcome "
>>> print (str14)
Welcome Welcome Welcome Welcome
(iv) String slicing:
➢ Slice is a substring of a main string.
➢ A substring can be taken from the original string by using [] operator and index or
subscript values.
Syntax:
str[start:end]
✓ Where start is the beginning index and end is the last index value of a character
in the string. Python takes the end value less than one from the actual index
specified.
Example:
>>> str1="THIRUKKURAL"
>>> print (str1[0])
T
>>> print (str1[0:5])
THIRU
(v) Stride when slicing string:
When the slicing operation, you can specify a third argument as the stride, which
refers to the number of characters to move forward after the first character is retrieved
from the string. The default value of stride is 1.
Example:
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
learn
>>> print (str1[10:16:2])
er
ADDITIONAL QUESTIONS
1. Which of the following is used to handle array of characters?
a) Word b) Character c) String d) Letters
2. Index values are otherwise called as
a) Size b) Length c) Superscript d) Subscript
3. The positive subscript of a string always starts from
a) 0 b) 1 c) 2 d) 3
4. The negative subscript of a string starts from
a) 0 b) 1 c) -1 d) 3
5. The operator used to append a new string with an existing string is
a) + b) += c) ++ d) *
6. The operator used to display a string in multiple number of times is
a) + b) & c) * d) ++
..57..
– 8. STRINGS AND STRING MANIPULATION
7. The string formatting operator is
a) % b) += c) ++ d) <>
8. The function which allows you to change all occurrences of a particular character in a string is
a) modify() b) change() c) replace() d) update()
9. Which of the following function returns the number of characters in a string?
a) len(str) b) str.len() c) length(str) d) str.length()
10. The function which returns the number of substrings occurs within the given range is
a) count() b) find() c) search() d) None of these
11. What is the output for the following code?
str = “School”
print(str[2])
a) c b) o c) h d) l
12. What is the output for the following code?
str = “School”
print(str[-2])
a) c b) o c) h d) l
13. What is the output for the following code?
str=”Computer”
print(str[0:5])
a) Compute b) Compu c) Computer d) Comput
14. What is the output for the following code?
str=”Cat”
str[0]=”B”
print(str)
a) Bat b) Cat c) CaB d) Error
15. Stride is a ________ argument in slicing operation.
a) first b) second c) third d) fourth
16. What is the output for the following code?
str=”Computer”
print(str[::2])
a) Comue b) Cmue c) mue d) Coptr
17. What is the output for the following code?
str1 = "Welcome to learn Python"
print(str1[::-2])
(a) o (b) otPnalo mce (c) nhy re teolW (d) e
18. What is the output for the following code?
str1=”Welcome”
print(str1.center(15,’*’))
a) ***Welcome***** b) *******Welcome*******
c) ****Welcome**** d) ****welcome****

..58..
– 8. STRINGS AND STRING MANIPULATION
19. How will you access characters in a string?
➢ Once you define a string, python allocate an index value for its each character.
➢ These index values are otherwise called as subscript which are used to access and
manipulate the strings. The subscript can be positive or negative integer numbers.
➢ The positive subscript 0 is assigned to the first character and n-1 to the last character,
where n is the number of characters in the string.
➢ The negative index assigned from the last character to the first character in reverse order
begins with -1.
Example:
String S C H O O L
Positive subscript 0 1 2 3 4 5
Negative subscript -6 -5 -4 -3 -2 -1
20. Write short note on replace() function.
➢ The replace() function is used to temporarily change all occurrences of a particular
character in a string.
➢ The changes done through replace () does not affect the original string.
Syntax:
replace(“char1”, “char2”)
✓ The replace function replaces all occurrences of char1 with char2.
Example:
>>> print (str1.replace("o", "e"))
Hew are yeu
21. What is the use of len() function? Give an example.
len() function returns the length (no of characters) of the string.
Example:
>>> A="Corporation"
>>> print(len(A))
11
22. What is the use of string formatting operators?
The string formatting operator % is used to construct strings, replacing parts of the strings
with the data stored in variables.
Syntax:
(“String to be display with %val1 and %val2” %(val1, val2))
Example:
name = "Rajarajan"
mark = 98
print ("Name: %s and Marks: %d" %(name,mark))
Output:
Name: Rajarajan and Marks: 98

..59..
– 8. STRINGS AND STRING MANIPULATION
23. List some of the formatting characters in Python.
Formatting
Usage
characters
%c Character
%d (or) %i Signed decimal integer
%s String
%u Unsigned decimal integer
%o Octal integer
Hexadecimal integer
%x or %X
(lower case x refers a-f; upper case X refers A-F)
%e or %E Exponential notation
%f Floating point numbers
%g or %G Short numbers in floating point or exponential notation.
24. Write short note on escape sequences in Python.
➢ Escape sequences starts with a backslash and it can be interpreted differently.
➢ When you have use single quote to represent a string, all the single quotes inside the
string must be escaped.
➢ Similar is the case with double quotes.
Escape Sequence Description
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quotes
\a ASCII Bell
\b ASCII Backspace
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH
25. What is the use of membership operators?
The ‘in’ and ‘not in’ operators can be used with strings to determine whether a string is
present in another string. Therefore, these operators are called as Membership Operators.
Example: Output 1:
str1=input ("Enter a string: ") Enter a string: Chennai G HSS
str2="Chennai" Found
if str2 in str1: Output 2:
print ("Found") Enter a string: Govt G HSS
else: Not Found
print ("Not Found")

..60..
– 8. STRINGS AND STRING MANIPULATION
26. Compare ord( ) and chr() functions.
ord(char ) chr(ASCII)
• Returns the ASCII code of the character. • Returns the character represented by a
• Example: ASCII.
>>> ch = 'A' • Example:
>>> print(ord(ch)) >>> ch=97
65 >>> print(chr(ch))
a
27. Explain the following built-in string functions.
a) isalpha() b) isdigit() c) islower() d) isupper() e) title()
Returns True if the string contains only >>>’Click123’.isalpha()
letters. Otherwise return False. False
isalpha()
>>>’python’.isalpha( )
True
Returns True if the string contains only >>> str1=’Save Earth’
isdigit() numbers. Otherwise it returns False. >>>print(str1.isdigit( ))
False
Returns True if the string is in lowercase. >>> str1=’welcome’
islower() >>>print (str1.islower( ))
True
Returns True if the string is in uppercase. >>> str1=’welcome’
isupper() >>>print (str1.isupper( ))
False
Returns a string in title case. >>> str1='education department'
title() >>> print(str1.title())
Education Department
28. What is the use of find() function? Give an example.
✓ The function is used to search the first occurrence of the sub string in the given string.
✓ It returns the index at which the substring starts.
✓ It returns -1 if the substring does not occur in the string.
Syntax:
find(substring, [start, end])
Example:
s=”Welcome to Python”
print(“The substring is in the position: ”, s.find(‘come’, 0, 10))
output:
The substring is in the position: 3

..61..
9 LISTS, TUPLES, SETS AND DICTIONARY

Part - I
Choose the best answer: (1 Mark)
1. Pick odd one in connection with collection data type
(A) List (B) Tuple (C) Dictionary (D) Loop
2. Let list1=[2,4,6,8,10], then print(List1[-2]) will result in
(A) 10 (B) 8 (C) 4 (D) 6
3. Which of the following function is used to count the number of elements in a list?
(A) count() (B) find() (C) len() (D) index()
4. If List=[10,20,30,40,50] then List[2]=35 will result
(A) [35,10,20,30,40,50] (B) [10,20,30,40,50,35]
(C) [10,20,35,40,50] (D) [10,35,30,40,50]
5. If List=[17,23,41,10] then List.append(32) will result
(A) [32,17,23,41,10] (B) [17,23,41,10,32]
(C) [10,17,23,32,41] (D) [41,32,23,17,10]
6. Which of the following Python function can be used to add more than one element within an
existing list?
(A) append() (B) append_more() (C) extend() (D) more()
7. What will be the result of the following Python code?
S=[x**2 for x in range(5)]
print(S)
(A) [0,1,2,4,5] (B) [0,1,4,9,16] (C) [0,1,4,9,16,25] (D) [1,4,9,16,25]
8. What is the use of type() function in python?
(A) To create a Tuple
(B) To know the type of an element in tuple.
(C) To know the data type of python object.
(D) To create a list.
9. Which of the following statement is not correct?
(A) A list is mutable
(B) A tuple is immutable.
(C) The append() function is used to add an element.
(D) The extend() function is used in tuple to add elements in a list.
10. Let setA={3,6,9}, setB={1,3,9}. What will be the result of the following snippet?
print(setA|setB)
(A) {3,6,9,1,3,9} (B) {3,9} (C) {1} (D) {1,3,6,9}
11. Which of the following set operation includes all the elements that are in two sets but not the
one that are common to two sets?
(A) Symmetric difference (B) Difference (C) Intersection (D) Union
12. The keys in Python, dictionary is specified by
(A) = (B) ; (C)+ (D) :

..62..
– 9. LISTS, TUPLES, SETS AND DICTIONARY
Part - II
Answer the following questions: (2 Marks)
1. What is List in Python?
A list in Python is known as a “sequence data type” like strings. It is an ordered collection
of values enclosed within square brackets []. Each value of a list is called as element.
2. How will you access the list elements in reverse order?
Python enables reverse or negative indexing for the list elements. Thus, python lists index
in opposite order. The python sets -1 as the index value for the last element in list and -2 for
the preceding element and so on. This is called as Reverse Indexing.
Example: Output:
Marks = [10, 23, 41, 75] 75
i = -1 41
while i >= -4: 23
print (Marks[i]) 10
i = i -1
3. What will be the value of x in following python code?
List1=[2,4,6,[1,3,5]]
x=len(List1)
The value of x is 4
4. Differentiate del with remove() function of List.
➢ del statement is used to delete elements whose index is known whereas remove()
function is used to delete elements of a list if its index is unknown.
➢ The del statement can also be used to delete entire list.
Example:
marks = [50, 63, 41, 75]
del marks[1] or marks.remove(63)
5. Write the syntax of creating a Tuple with n number of elements.
Tuple_Name = (E1, E2, E2 ……. En)
(Or)
Tuple_Name = E1, E2, E3 ….. En
6. What is set in Python?
A Set is a mutable and an unordered collection of elements without duplicates. That
means the elements within a set cannot be repeated.
Part - III
Answer the following questions: (3 Marks)
1. What are the difference between list and of Tuples ot?
List Tuples
The elements of a list are changeable The elements of a tuple are unchangeable
(mutable) (immutable)

..63..
– 9. LISTS, TUPLES, SETS AND DICTIONARY
The elements are enclosed within square The elements are enclosed by parenthesis.
brackets.
Iteration is slow. Iteration is faster.
2. Write a short note about sort( ).
sort() function arranges a list value in ascending order by default.
Syntax:
list.sort([reverse=True|False, key=myFunc])
✓ Both arguments are optional.
✓ If reverse is set as True, list sorting is in descending order.
Example: Output:
MyList=[5,2,3,4,1] [1,2,3,4,5]
MyList.sort( ) [5,4,3,2,1]
print(MyList)
MyList.sort(reverse=True)
print(MyList)
3. What will be the output of the following code?
list = [2x for x in range(5)]
print(list)
Output:
[1, 2, 4, 8, 16]
4. Explain the difference between del and clear() in dictionary with an example.
➢ In Python dictionary, del keyword is used to delete a particular element.
➢ The clear() function is used to delete all the elements in a dictionary.
➢ To remove the dictionary, you can use del keyword with dictionary name.
Example: Output:
Dict = {'Mark1' : 98, 'Marl2' : 86} {'Mark2': 86}
del Dict['Mark1'] {}
print(Dict) NameError: name 'Dict' is not defined
Dict.clear()
print(Dict)
del Dict
print(Dict)
5. List out the set operations supported by python.
(i) Union (I) : It includes all elements from two or more sets
(ii) Intersection (&): It includes the common elements in two sets
(iii) Difference (-):
It includes all elements that are in first set (say set A) but not in the second set (say set B)
(iv) Symmetric difference (^):
It includes all the elements that are in two sets (say sets A and B) but not the one that are
common to two sets.

..64..
– 9. LISTS, TUPLES, SETS AND DICTIONARY
6. What are the differences between List and Dictionary?
List Dictionary
List is an ordered set of elements. Dictionary is a data structure that is used for
matching one element (Key) with another
(Value).
The index values can be used to access a In dictionary key represents index.
particular element.
Lists are used to look up a value. It is used to take one value and look up
another value.
Part - IV
Answer the following questions: (5 Marks)
1. What the different ways to insert an element in a list. Explain with suitable example.
There are three methods are used to insert the elements in a list.
(i) append():
In Python, append( ) function is used to add a single element to an existing list.
Syntax:
List.append(element to be added)
Example:
>>>Marks = [10, 23, 41, 75]
>>>Marks.append(60)
>>>print(Marks)
[10, 23, 41, 75, 60]
(ii) extend():
In python, extend( ) function is used to add more than one element to an existing list.
Syntax:
List.extend([elements to be added])
Example:
>>>Marks = [10, 23, 41, 75]
>>>Marks.extend([60,80,55])
>>>print(Marks)
[10, 23, 41, 75, 60,80,55]
(iii) insert():
The insert( ) function is used to insert an element at any desired position of a list.
Syntax:
List.insert (position index, element)
Example:
>>>Marks = [10, 23, 41, 75]
>>>Marks.insert(2,60)
>>>print(Marks)
[10, 23, 60, 41, 75]
While inserting a new element in between the existing elements, at a particular location,
the existing elements shifts one position to the right.

..65..
– 9. LISTS, TUPLES, SETS AND DICTIONARY
2. What is the purpose of range( )? Explain with an example.
i. The range( ) is a function used to generate a series of values in Python.
ii. Using range( ) function, you can create list with series of values.
i. Syntax:
range (start value, end value, step value)
where,
✓ start value – beginning value of series
✓ end value – final value of series.
✓ step value – It is an optional argument, which refers to increment value.
Example: Output:
for x in range (2, 11, 2): 2 4 6 8 10
print(x, end=’ ’)
ii. Creating a list with range() function:
➢ Using the range( ) function, you can create a list with series of values.
➢ The list( ) function makes the result of range( ) as a list.
Syntax:
List_Varibale = list (range())
Example:
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)
[2, 4, 6, 8, 10]
In the above code, list( ) function takes the result of range( ) as Even_List elements.
3. What is nested tuple? Explain with an example.
➢ In Python, a tuple can be defined inside another tuple; called Nested tuple.
➢ In a nested tuple, each tuple is considered as an element.
➢ The for loop will be useful to access all the elements in a nested tuple.
Example:
voters=(("Aruna", "F", 36), ("Suriya", "M", 35), ("Kamal", "M", 23))
for i in voters:
print(i)
Output:
(‘Aruna’, ‘F’, 36)
('Suriya', ‘M', 35)
(‘Kamal’, 'M', 23)
4. Explain the different set operations supported by python with suitable example.
Python supports the set operations such as Union, Intersection, Difference and Symmetric
difference.
(i) Union:
➢ It includes all elements from two or more sets.
➢ In python, the operator | and the function union( ) are used to join two sets in python.

..66..
– 9. LISTS, TUPLES, SETS AND DICTIONARY
Example: Output:
set_A = {2,4,6,8} {2, 4, 6, 8, 'A', 'D', 'C', 'B'}
set_B = {'A', 'B', 'C', 'D'}
print(set_A|set_B) (OR) print(set_A.union(set_B)
(ii) Intersection:
➢ It includes the common elements in two sets.
➢ The operator & and the function intersection( ) are used to intersect two sets in
python.
Example: Output:
set_A={'A', 2, 4, 'D'} {'A', 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B) (OR) print(set_A.intersection(set_B))
(iii) Difference:
➢ It includes all elements that are in first set but not in the second set.
➢ The minus (-) operator and the function difference( ) are used to difference
operation.
Example: Output:
set_A={'A', 2, 4, 'D'} {2, 4}`
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B) (OR) print(set_A.difference(set_B))
(iv) Symmetric difference:
➢ It includes all the elements that are in two sets but not the one that are common to
two sets.
➢ The caret (^) operator and the function symmetric_difference() are used to
symmetric difference set operation in python.
Example: Output:
set_A={'A', 2, 4, 'D'} {2, 4, 'B', 'C'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B) (OR) print(set_A.symmetric_difference(set_B))
ADDITIONAL QUESTIONS
1. Which of the following is not a “sequence data type”?
a) List b) Tuples c) Set d) String
2. It is an ordered collection of values enclosed within square brackets [ ].
a) Tuples b) Set c) List d) Dictionary
3. Which of the following consists of a number of values separated by comma and enclosed
within parentheses?
a) Tuples b) Set c) List d) Dictionary
4. Which of the following is a mutable and an unordered collection of elements without duplicates?
a) List b) Tuple c) Set d) Dictionary
5. Which type stores a key along with its element?
a) List b) Tuple c) Set d) Dictionary
..67..
– 9. LISTS, TUPLES, SETS AND DICTIONARY
6. Which of the following is the correct way of creating list?
I. Marks = [10,20,30,40]
II. Fruits = [“Apple”,”Orange”,”Mango”,”Banana”]
III. Mylist = []
IV. Data = [“Welcome”, 3.14,10,[5,10]]
a) I, II Only b) I, II, III Only
c) All are wrong d) All are correct
7. What is the output for the following code?
Marks = [10,23,41,75]
print(Marks[-3])
a) 10 b) 23 c) 41 d) 75
8. What is the output for the following code?
List = [10,20,30,[40,50,60],70]
print(len(List))
a) 7 b) 6 c) 5 d) 3
9. Which of the following represents A={10,20,30 }?
a) List b) Tuple c) Dictionary d) Set
10. What is the output for the following code?
li = list(range(2,11,2))
print(li)
a) [1,3,5,7,9] b) [2,4,6,8,10]
c) [2,4,6,8] d) [1,2,3,4,5,6,7,8,9,10]
11. What is the output for the following code?
S=[x**2 for x in range(1,11)]
print(S)
a) [1,2,3,4,5,6,7,8,9,10] b) [1,2,3,4,5,6,7,8,9,10,11]
c) [1,4,9,16,25,36,49,64,81,100] d) [2,4,6,8,10]
12. What is the output for the following code?
mylist=[36,12,12]
x=mylist.index(12)
print(x)
a) 0 b) 1 c) -1 d) 2
13. Which of the following represents A={roll:101,age:25,name:'ABC' }?
(a) List b) Tuple c) Dictionary d) Set
14. What is the output for the following code?
>>> S1={1,2,2,’A’,3.14}
>>> print(S1)
a) {1,2,’A’,3.14} b) {1,2,2,’A’,3.14} c) Error d) No Output
15. What is the output for the following code?
>>> Dict = {x : 2 * x for x in range(1,4)}
a) {1:2,2:4,3:9,4:16,5:25} b) {1:2,2:4,3:6} c) {1:2,2:4,4:16} d) {}
..68..
– 9. LISTS, TUPLES, SETS AND DICTIONARY
16. L=[2,4,7,11,15] – the negative index represents 11 is
a) -4 b) -1 c) -3 d) -2
17. L=[2,4,7,11,15] - the positive index represents 11 is
a) 4 b) 3 c) 2 d) 0
18. Which of the following function is used to know the data type of a python object?
a) data() b) type() c) format() d) datatype()
19. The correct way of declaring a tuple with one element is
a) tup=(10,) b) tup=(10.) c) tup=(10-) d) tup=(10);
20. The function used to delete all elements in a dictionary is
a) del() b) clear() c) delete() d) clean()
21. How will you create a list in python?
In python, a list is simply created by using square bracket. The elements of list should be
specified within square brackets.
Syntax:
Variable = [element-1, element-2, element-3 …… element-n]
Example:
Marks = [10, 23, 41, 75]
22. Write short note on List comprehension.
List comprehension is a simplest way of creating sequence of elements that satisfy a
certain condition.
Syntax:
List = [ expression for variable in range ]
Example: Output:
>>> squares = [ x ** 2 for x in range(1,11) ] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> print (squares)
23. How can you access the list elements?
➢ Index value can be used to access an element in a list. In python, index value is an integer
number which can be positive or negative.
➢ Positive value of index counts from the beginning of the list and negative value means
counting backward from end of the list (i.e. in reverse order).
Example:
(1) >>> Marks = [10, 23, 41, 75] (2) >>> Marks = [10, 23, 41, 75]
>>> print (Marks[0]) >>> print (Marks[-1])
10 75
24. How can you access all the list elements using for loop?
In Python, the for loop is used to access all the elements in a list one by one.
Syntax:
for index_var in List:
print (index_var)
✓ Here, index_var represents the index value of each element in the list.

..69..
– 9. LISTS, TUPLES, SETS AND DICTIONARY
Example: Output:
Marks=[20, 40, 60] 20
for x in Marks: 40
print(x) 60
25. Write the use of POP() function in Python.
➢ pop() function is used to delete a particular element using its index value, as soon as the
element is deleted, the pop() function shows the element which is deleted.
➢ pop() function deletes and returns the last element of a list if the index is not given.
26. What is Singleton tuple?
Creating a Tuple with one element is called “Singleton” tuple.
Example:
t1 = (10,)
27. How can you create tuples using tuple( ) function?
➢ The tuple() function is used to create Tuples from a list.
➢ When you create a tuple, from a list, the elements should be enclosed within square
brackets.
Syntax:
Tuple_Name = tuple( [list elements] )
Example: Output:
>>> t1 = tuple([23, 45, 90] ) (23, 45, 90)
>>> print(t1) <class ‘Tuples’>
>>> type (t1)
28. What is meant by tuple assignment?
Tuple assignment is a powerful feature in Python. It allows a tuple variable on the left of
the assignment operator to be assigned to the values on the right side of the assignment
operator. Each value is assigned to its respective variable.
Example:
>>> (a, b, c) = (34, 90, 76)
>>> print(a,b,c)
34 90 76
29. What is Dictionary?
➢ In python, a dictionary is a mixed collection of elements. Unlike other collection data
types such as a list or tuple, the dictionary type stores a key along with its element.
➢ The keys in a Python dictionary is separated by a colon ( : ) while the commas work as a
separator for the elements.
➢ The key value pairs are enclosed with curly braces { }.
30. Write the syntax of Dictionary creation.
Dictionary_Name = { Key_1: Value_1, Key_2:Value_2, …….. Key_n:Value_n }
31. Dict = { x : 2 * x for x in range(1,10)} - Write the output of this statement.
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

..70..
10 PYTHON CLASSES AND OBJECTS

Part - I
Choose the best answer: (1 Mark)
1. Which of the following are the key features of an Object-Oriented Programming language?
(A) Constructor and Classes (B) Constructor and Object
(C) Classes and Objects (D) Constructor and Destructor
2. Functions defined inside a class:
(A) Functions (B) Module (C) Methods (D) section
3. Class members are accessed through which operator?
(A) & (B) . (C) # (D) %
4. Which of the following method is automatically executed when an object is created?
(A) __object__( ) (B) __del__( ) (C) __func__( ) (D) __init__( )
5. A private class variable is prefixed with
(A) __ (B) && (C) ## (D) **
6. Which of the following method is used as destructor?
(A) __init__( ) (B) __dest__( ) (C) __rem__( ) (D) __del__( )
7. Which of the following class declaration is correct?
(A) class class_name (B) class class_name<>
(C) class class_name: (D) class class_name[ ]
8. Which of the following is the output of the following program?
class Student:
def __init__(self, name):
self.name=name
print (self.name)
S=Student(“Tamil”)
(A) Error (B) Tamil (C) name (D) self
9. Which of the following is the private class variable?
(A) __num (B) ##num (C) $$num (D) &&num
10. The process of creating an object is called as:
(A) Constructor (B) Destructor (C) Initialize (D) Instantiation
Part - II
Answer the following questions: (2 Marks)
1. What is class?
Class is a template for the object. It is the main building block in Python.
2. What is instantiation?
The process of creating object is called as “Class Instantiation”.
3. What is the output of the following program?
class Sample:
__num=10

..71..
– 10. PYTHON CLASSES AND OBJECTS
def disp(self):
print(self.__num)
S=Sample()
S.disp()
print(S.__num)
Output:
10
Attribute Error: 'Sample' object has no attribute '__num'
4. How will you create constructor in Python?
➢ In Python, Constructor is the special function called “init” that is automatically executed
when an object of a class is created.
➢ It must begin and end with double underscore.
Syntax:
def __init__(self, [args ……..]):
<statements>
Example: Output:
class Sample: Constructor of class Sample...
def __init__(self):
print("Constructor of class Sample...")
S=Sample()
5. What is the purpose of Destructor?
➢ Destructor is also a special method to destroy the objects.
➢ In Python, __del__( ) method is used as destructor. It is just opposite to constructor.
Part - III
Answer the following questions: (3 Marks)
1. What are class members? How do you define it?
➢ Variables and functions defined inside a class are called as “Class Variable” and “Methods”
respectively.
➢ Class variable and methods are together known as members of the class.
Example:
class Sample:
x = 10 → class variable
def disp(self): → method
print(Sample.x)
s = Sample()
s.disp()
2. Write a class with two private class variables and print the sum using a method.
Program:
class sample:
def __init__(self,n1,n2):
self.__n1=n1
self.__n2=n2
..72..
– 10. PYTHON CLASSES AND OBJECTS
def sum(self):
print(self.__n1 + self.__n2)
s=sample(12,14)
s.sum()
3. Find the error in the following program to get the given output?
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple', 'Mango')
del F.display
F.display()
Output:
Fruit 1 = Apple, Fruit 2 = Mango
Error:
The statement “del F.display” should be removed to get the given output.
4. What is the output of the following program?
class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Good Morning ", self.__name)
obj=Greeting('Bindu Madhavan')
obj.display()
Output:
Good Morning Bindu Madhavan
5. How do define constructor and destructor in Python?
Syntax of Constructor:
def __init__(self, [args ……..]):
<statements>
Syntax of Destructor:
def __del__(self):
<statements>
Example: Output:
class sample: Constructor of class Sample...
def __init__(self,n1): Destructor of class Sample...
self.__n1=n1
print("Constructor of class Sample...")
def __del__(self):
print("Destructor of class Sample...")
s=sample(5)
..73..
– 10. PYTHON CLASSES AND OBJECTS
Part - IV
Answer the following questions: (5 Marks)
1. Explain about constructor and destructor with suitable example.
Constructor:
Constructor is the special function that is automatically executed when an object of a class
is created. In Python, there is a special function called “init” which act as a Constructor. It must
begin and end with double underscore.
Syntax:
def __init__(self, [args ……..]):
<statements>
Example:
def __init__(self, [args ……..]):
<statements>
class Sample:
def __init__(self, num):
print("Constructor of class Sample...")
self.num=num
print("The value is :", num)
S=Sample(10)
✓ The above constructor gets executed automatically, when an object S is created with actual
parameter 10.
Thus, the Python display the following output.
Constructor of class Sample...
The value is : 10
Destructor:
Destructor is also a special method to destroy the objects. It gets executed automatically
when an object exits from the scope. In Python, __del__( ) method is used as destructor. It is
just opposite to constructor.
Syntax:
def __del__(self):
<statements>
Example:
class sample:
def __del__(self):
print("Destructor of class Sample...")
s=sample(5)
✓ In the example above, when the accessibility of the object S goes out of scope, the
destructor is executed automatically.
Thus, the Python display the following output.
Destructor of class Sample...

..74..
– 10. PYTHON CLASSES AND OBJECTS
ADDITIONAL QUESTIONS
1. Which of the following is not an object-oriented programming language?
a) C b) C++ c) Python d) Java
2. The key features of Object-Oriented Programming are
a) Classes b) Objects c) a) and b) d) Structures
3. Which one is referred as instance of a class?
a) Class b) Object c) Methods d) Members
4. In Python, by default the variables which are defined inside the class is
a) Private b) Public c) Protected d) Hidden
5. Any class member can be accessed by using object with a ____ operator.
a) Semicolon(;) b) Hash(#) c) Colon(:) d) Dot(.)
6. Which of the following will act as a constructor?
a) _ _init b) _ _self_ _ c) _ _del_ _ d) _ _init_ _
7. Which of the following is used to initialize the class variables?
a) Class b) Object c) Constructor d) Destructor
8. In Python, a class is defined by using the keyword
a) this b) self c) class d) def
9. In Python, every class has a unique name followed by
a) Semicolon(;) b) Period(.) c) Colon(:) d) None
10. The class method must have the first parameter named as
a) this b) self c) class d) def
11. A variable prefixed with double underscore becomes
a) Private b) Public c) Protected d) Hidden
12. Which of the following variables can be accessed only within the class?
a) Private b) Public c) Protected d) Hidden
13. A variable accessed anywhere in the program is
a) Private b) Public c) Protected d) Hidden
14. The statements defined inside the class must be properly
a) indented b) left space c) placed a colon d) All of these
15. It gets executed automatically when an object exits from the scope.
a) Class b) Object c) Constructor d) Destructor
16. How would you define a class in Python?
In Python, a class is defined by using the keyword class. Every class has a unique name
followed by a colon ( : ).
Syntax: Exmple:
class class_name: class Student:
statement_1 mark1, mark2 = 45, 91
statement_2 def process(self):
………….. sum=Student.mark1+Student.mark2
…………..
statement_n
✓ Where, statement in a class definition may be a variable declaration, decision
control, loop or even a function definition.
..75..
– 10. PYTHON CLASSES AND OBJECTS
17. How will you create objects for a class?
Once a class is created, next you should create an object or instance of that class. The
process of creating object is called as “Class Instantiation”.
Syntax:
Object_name = class_name( )
Example:
class Sample:
x, y = 10, 20
S=Sample( )
✓ In class instantiation process, we have created an object ‘S’ to access the members
of the class.
18. How will you access class members?
Any class member ie. class variable or method (function) can be accessed by using object
with a dot ( . ) operator.
Syntax:
Object_name . class_member
Example: Output:
class Sample: Value of x = 10
x, y = 10, 20 Value of y = 20
S=Sample( )
print("Value of x = ", S.x)
print("Value of y = ", S.y)
19. What is the use of private and public data members?
➢ The variables which are defined inside the class is public by default. These variables can
be accessed anywhere in the program using dot operator.
➢ A variable prefixed with double underscore becomes private in nature. These variables
can be accessed only within the class.
20. Write about class methods.
➢ Python class function or Method is very similar to ordinary function with a small
difference that, the class method must have the first argument named as self.
➢ No need to pass a value for this argument when we call the method. Python provides its
value automatically. Even if a method takes no arguments, it should be defined with the
first argument called self.
➢ If a method is defined to accept only one argument it will take it as two arguments ie. self
and the defined argument.
➢ When you declare class variable within class, methods must be prefixed by the class name
and dot operator.

..76..
11 DATABASE CONCEPTS

Part - I
Choose the best answer: (1 Mark)
1. What is the acronym of DBMS?
(A) DataBase Management Symbol (B) Database Managing System
(C) DataBase Management System (D) DataBasic Management System
2. A table is known as
(A) tuple (B) attribute (C) relation (D) entity
3. Which database model represents parent-child relationship?
(A) Relational (B) Network (C) Hierarchical (D) Object
4. Relational database model was first proposed by
(A) E F Codd (B) E E Codd (C) E F Cadd (D) E F Codder
5. What type of relationship does hierarchical model represents?
(A) one-to-one (B) one-to-many
(C) many-to-one (D) many-to-many
6. Who is called Father of Relational Database from the following?
(A) Chris Date (B) Hugh Darween
(C) Edgar Frank Codd (D) Edgar Frank Cadd
7. Which of the following is an RDBMS?
(A) Dbase (B) Foxpro (C) Microsoft Access (D) MS Excel
8. What symbol is used for SELECT statement?
(A) σ (B) Π (C) X (D) Ω
9. A tuple is also known as
(A) table (B) row (C) attribute (D) field
10. Who developed ER model?
(A) Chen (B) EF Codd (C) Chend (D) Chand
Part - II
Answer the following questions: (2 Marks)
1. Mention few examples of a database.
 Dbase  Oracle  MySQL
 FoxPro  MS-Access  SQL SERVER
2. List some examples of RDBMS.
 Oracle  MySQL  MS-Access  SQLITE
 SQL SERVER  IBM DB2  MARIADB
3. What is data consistency?
❖ Data Consistency means that data values are the same at all instances of a database.
❖ Data consistency is the process of dealing with the consistency of live data that is
constantly updated and maintained.
4. What is the difference between Hierarchical and Network data model?
❖ In hierarchical model, a child record has only one parent node.

..77..
– 11. DATABASE CONCEPTS
❖ In a Network model, a child may have many parent nodes. It represents the data in
many-to-many relationships.
❖ This model is easier and faster to access the data.
5. What is normalization?
Database normalization was first proposed by Dr. Edgar F Codd as an integral part of
RDBMS in order to reduce data redundancy and improve data integrity.
Part - III
Answer the following questions: (3 Marks)
1. What is the difference between Select and Project command?
Select Project
The SELECT operation is used for selecting a The projection eliminates all attributes of
subset with tuples according to a given the input relation but those mentioned in
condition. the projection list.
Select filters out all tuples that do not satisfy The projection method defines a relation
the condition. that contains a vertical subset of Relation.
symbol : σ symbol : ∏
2. What is the role of DBA?
➢ Database Administrator or DBA is the one who manages the complete database
management system.
➢ DBA takes care of the security of the DBMS, managing the license keys, managing user
accounts and access etc.
3. Explain Cartesian product with a suitable example.
❖ Cross product is a way of combining two relations. The resulting relation contains, both
relations being combined.
❖ A x B means A times B, where the relation A and B have different attributes.
Table A Table B
RollNo Name SubCode Subject
1051 Aakash 041 Maths
1052 Subitha 019 Computer Science
Cartesian product : Table A x Table B
RollNo Name SubCode Subject
1051 Aakash 041 Maths
1051 Aakash 019 Computer Science
1052 Subitha 041 Maths
1052 Subitha 019 Computer Science
4. Explain Object Model with example.
❖ Object model stores the data in the form of objects, attributes and methods, classes and
Inheritance.
❖ This model handles more complex applications, such as Geographic information System
(GIS), scientific experiments, engineering design and manufacturing.

..78..
– 11. DATABASE CONCEPTS
❖ It is used in file Management System.
❖ It represents real world objects, attributes and behaviours.
5. Write a note on different types of DBMS users.
➢ Database Administrators:
Database Administrator or DBA is the one who manages the complete database
management system. DBA takes care of the security of the DBMS, managing the license
keys, managing user accounts and access etc.
➢ Application Programmers or Software Developers:
This user group is involved in developing and designing the parts of DBMS.
➢ End User:
End users are the one who store, retrieve, update and delete data.
➢ Database designers:
Are responsible for identifying the data to be stored in the database for choosing
appropriate structures to represent and store the data.
Part - IV
Answer the following questions: (5 Marks)
1. Explain the different types of data model.
1. Hierarchical Model:
➢ Hierarchical model was developed by IBM.
➢ In Hierarchical model, data is represented as a simple tree like structure form. This model
represents a one-to-many relationship i.e parent-child relationship.
➢ One child can have only one parent but one parent can have many children.
➢ This model is mainly used in IBM Main Frame computers.

School

Course Resources

Theory Lab

2. Relational Model:
➢ The Relational Database model was first proposed by E.F. Codd in 1970.
➢ Nowadays, it is the most widespread data model used for database applications
around the world.
➢ The basic structure of data in relational model is tables (relations).
➢ All the information’s related to a particular type is stored in rows of that table.
➢ A relation key is an attribute which uniquely identifies a particular tuple.

..79..
– 11. DATABASE CONCEPTS
Stu_id Name Age Sub_id Subject Teacher
1 Aruna 17 1 Tamil Jegan
2 Prabhakar 16 2 Maths Veni
3 Aakash 15 3 Science Jeya

Stu_id Sub_id Marks


1 1 98
2 2 87
3 2 75

3. Network Model:
➢ Network database model is an extended form of hierarchical data model.
➢ The difference between hierarchical and Network data model is:
❖ In hierarchical model, a child record has only one parent node.
❖ In a Network model, a child may have many parent nodes. It represents the
data in many-to-many relationships.
❖ This model is easier and faster to access the data.

School Parent Node

Library Office Staff Room Child to School (Parent Node)

Student has 3 Parents


Student
(one to many relationship)

4. Entity Relationship Model (ER model):


➢ In this database model, relationships are created by dividing the object into entity and
its characteristics into attributes.
➢ It was developed by Chen in 1976.
➢ This model is useful in developing a conceptual design for the database.
➢ It is very simple and easy to design logical view of data.
➢ The different shapes used in ER diagram is
✓ Rectangle represents the entities.
Example: Doctor and Patient
✓ Ellipse represents the attributes.
Example: D-id, D-Name, P-id and P-Name
✓ Diamond represents the relationships.
Example: Doctor diagnosis the Patient

..80..
– 11. DATABASE CONCEPTS

Doctor Patient
Diagnosis

D-id D-Name P-id P-Name

5. Object Model:
➢ Object model stores the data in the form of objects, attributes and methods, classes
and Inheritance.
➢ This model handles more complex applications, such as Geographic information
System (GIS), scientific experiments, engineering design and manufacturing.
➢ It is used in file Management System.
➢ It represents real world objects, attributes and behaviours.
Example:

Shape
get_area()
get_perimeter(
)

Circle Rectangle Triangle


radius length base
breadth height

where,
✓ Shape is the class.
✓ Circle, Rectangle and Triangle are objects of class Shape.
✓ radius, length, breadth, base and height are attributes.
✓ get_area() and get_perimeter() are the methods.
2. Explain the different types of relationship mapping. Student Exam No
1. One-to-One Relationship:
➢ In One-to-One Relationship, one entity is related
with only one other entity. Rifayah 1001
➢ One row in a table is linked with only one row in
another table and vice versa. Vignes 1002
For example: h
A student can have only one exam number. Anand 1003

..81..
– 11. DATABASE CONCEPTS
2. One-to-Many Relationship: Staff
Department
➢ In One-to-Many relationship, one entity is
related to many other entities. Jeeya
➢ One row in a table A is linked to many rows in Tamil Aruna
a table B, but one row in a table B is linked to
only one row in table A. Maths Prabhu
For example:
Computer Anand
One Department has many staff members.
Raja

3. Many-to-One Relationship:
Staff Department
➢ In Many-to-One Relationship, many entities can
be related with only one in the other entity.
➢ Multiple rows in staff members table is related Rifayah Maths
with only one row in Department table.
For example: Vignesh Computer
A number of staff members working in one
Anand
Department.

4. Many-to-Many Relationship:
Book Student
A many-to-many relationship occurs when
multiple records in a table are associated with multiple
records in another table. Python Sumitha
For example:
Many Books in a Library are issued to many SQL Jingsily
students.
C++ Anbu

3. Differentiate DBMS and RDBMS.


Basis of
DBMS RDBMS
Comparison
Relational DataBase
Expansion Database Management System
Management System
Relational model (in tables).
Navigational model i.e. data by
Data storage i.e. data in tables as row and
linked records
column
Data redundancy Exhibit Not Present
RDBMS uses normalization to
Normalization Not performed
reduce redundancy

..82..
– 11. DATABASE CONCEPTS
Data access Consumes more time Faster, compared to DBMS.
used to establish relationship.
Keys and indexes Does not use.
Keys are used in RDBMS.
management Inefficient, Error
Transaction Efficient and secure.
prone and insecure.
Distributed Databases Not supported Supported by RDBMS.
SQL server, Oracle, Mysql,
Example Dbase, FoxPro
MariaDB, MS-Access.
4. Explain the different operators in Relational algebra with suitable examples.
I. Unary Relational Operations:
SELECT (symbol : σ)
➢ General form σc ( R ) with a relation R and a condition C on the attributes of R.
➢ The SELECT operation is used for selecting a subset with tuples according to a given
condition.
➢ Select filters out all tuples that do not satisfy C.
STUDENT
Studno Name Course Year
cs1 Kannan Big Data II
cs2 Gowri Shankar R language I
cs3 Lenin Big Data I
cs4 Padmaja Python Programming I

σcourse = “Big Data” (STUDENT )

Studno Name Course Year


cs1 Kannan Big Data II
cs3 Lenin Big Data I
PROJECT (symbol : Π)
➢ The projection eliminates all attributes of the input relation but those mentioned in the
projection list.
➢ The projection method defines a relation that contains a vertical subset of Relation.
Example:
Πcourse (STUDENT)
Result
Course
Big Data
R language
Python Programming

..83..
– 11. DATABASE CONCEPTS
II. Relational Algebra Operations from Set Theory:
For example, consider the following tables
Table A Table B

Studno Name Studno Name

cs1 Kannan cs1 Kannan

cs3 Lenin cs2 GowriShankarn

cs4 Padmaja cs3 Lenin

UNION (Symbol :∪)


➢ It includes all tuples that are in tables A or in B. It also eliminates duplicates.
➢ Set A Union Set B would be expressed as A ∪ B
Result
Table A ∪ B
Studno Name
cs1 Kannan
cs2 GowriShankar
cs3 Lenin
cs4 Padmaja

SET DIFFERENCE (Symbol : -)


➢ The result of A – B, is a relation which includes all tuples that are in A but not in B.
➢ The attribute name of A has to match with the attribute name in B and the result is,
Result
Table A - B
Studno Name
cs4 Padmaja

INTERSECTION (symbol: ∩) A ∩ B
➢ Defines a relation consisting of a set of all tuple that are in both in A and B. However, A
and B must be union-compatible.
Result
A∩B
Studno Name
cs1 Kannan
cs3 Lenin

..84..
– 11. DATABASE CONCEPTS
PRODUCT OR CARTESIAN PRODUCT (Symbol: X)
➢ Cross product is a way of combining two relations. The resulting relation contains, both
relations being combined.
➢ A x B means A times B, where the relation A and B have different attributes.
Table A Table B
RollNo Name SubCode Subject
1051 Aakash 041 Maths
1052 Subitha 019 Computer Science
Cartesian product : Table A x Table B
RollNo Name SubCode Subject
1051 Aakash 041 Maths
1051 Aakash 019 Computer Science
1052 Subitha 041 Maths
1052 Subitha 019 Computer Science
5. Explain the characteristics of RDBMS.
1. Ability to manipulate RDBMS provides the facility to manipulate data (store,
data modify and delete) in a database.
RDBMS follows Normalisation which divides the data in such
2. Reduced Redundancy
a way that repetition is minimum.
On live data, it is being continuously updated and added,
3. Data Consistency maintaining the consistency of data can become a challenge.
But RDBMS handles it by itself.
RDBMS allows multiple users to work on it (update, insert,
4. Support Multiple user
delete data) at the same time and still manages to maintain
and Concurrent Access
the data consistency.
RDBMS provides users with a simple query language, using
5. Query Language which data can be easily fetched, inserted, deleted and
updated in a database.
The RDBMS also takes care of the security of data, protecting
6. Security
the data from unauthorized access.
It allows us to better handle and manage data integrity in real
7. DBMS Supports
world applications where multi-threading is extensively used.
ADDITIONAL QUESTIONS
1. Which are raw facts stored in a computer?
a) Tables b) Database c) Information d) Data
2. Which of the following gives a meaningful information about the data?
a) Information b) Database c) DBMS d) Tables
3. How many major components are there in DBMS?
a) 3 b) 5 c) 7 d) 4
4. A row is also known as
a) Attribute b) Tuple c) Relation d) Data

..85..
– 11. DATABASE CONCEPTS
5. A column is known as
a) Attribute b) Tuple c) Relation d) Data
6. Hierarchical model was developed by
a) Windows b) IBM c) Wipro d) Apple
7. The entire collection of related data in one table is referred as
a) Relation b) Table c) File d) All of these
8. This model is mainly used in IBM Main Frame computers.
a) Hierarchical Model b) Object Model
c) Entity Relationship Model d) Relational Model
9. The relational database model was first proposed by E.F.Codd in
a) 1960 b) 1970 c) 1980 d) 1990
10. ER Model was developed by Chen in
a) 1966 b) 1970 c) 1972 d) 1976
11. In ER Model, the entities are represented by
a) Rectangle b) Ellipse c) Diamond d) Circle
12. In ER Model, the attributes are represented by
a) Rectangle b) Ellipse c) Diamond d) Circle
13. In ER Model, ________ represents the relationship in ER diagrams.
a) Rectangle b) Ellipse c) Diamond d) Circle
14. RDBMS Stands for
a) Rotational Database Management System b) Real Database Management System
c) Relational Database Management System d) Round Database Management System
15. In which of the following model, data is represented as a simple tree like structure?
a) Hierarchical Model b) Object Model
c) Network Model d) Relational
16. Database Normalization was first proposed by
a) Dr. Edgar F Codd b) Dr. Edgar E Codd c) Chen d) E F Chen
17. In which of the following relationship one row in a table is linked with only one row in another
table?
a) One-to-One b) One-to-Many
c) Many-to-One d) Many-to-Many
18. A student can have only one exam number is an example of
a) One-to-One Relationship b) One-to-Many Relationship
c) Many-to-One Relationship d) Many-to-Many Relationship
19. Many books in a Library are issued to many students is an example for
a) One-to-One Relationship b) One-to-Many Relationship
c) Many-to-One Relationship d) Many-to-Many Relationship
20. The symbol used for Cartesian product is
a) π b) α c) X d) *
21. The symbol used for PROJECT is
a) π b)  c) X d) ᓂ

..86..
– 11. DATABASE CONCEPTS
22. What is Data?
Data are raw facts stored in a computer. A data may contain any character, text, word or a
number.
Example: Vijay, 15
23. What is an Information?
Information is processed data, organized and formatted; it gives a meaningful information.
Example: Vijay is 15 years old.
24. What is database?
Database is a repository collection of related data organized in a way that data can be
easily accessed, managed and updated.
25. What is DBMS?
➢ A DBMS is a software that allows us to create, define and manipulate database, allowing
users to store, process and analyse data easily.
➢ DBMS provides us with an interface or a tool, to perform various operations to create a
database, storing of data and for updating data, etc.
➢ DBMS also provides protection and security to the databases.
➢ It also maintains data consistency in case of multiple users.
26. What are the advantages of RDBMS?
➢ Segregation of application program
➢ Minimal data duplication or Data Redundancy
➢ Easy retrieval of data using the Query Language
➢ Reduced development time and maintenance
27. What is Data Model?
❖ A data model describes how the data can be represented and accessed from a software
after complete implementation.
❖ It is a simple abstraction of complex real world data gathering environment.
❖ The main purpose of data model is to give an idea as how the final system or software
will look like after development is completed.
28. What is Relational Algebra?
❖ Relational Algebra, was first created by Edgar F Codd while at IBM.
❖ It was used for modelling the data stored in relational databases and defining queries on it.
❖ Relational Algebra is a procedural query language used to query the database tables using
SQL.
29. Explain the components of DBMS.
The Database Management System can be divided into five major components as follows:
1. Hardware:
The computer, hard disk, I/O channels for data, and any other physical component
involved in storage of data.
2. Software:
This main component is a program that controls everything. The DBMS software is
capable of understanding the Database Access Languages and interprets into database
commands for execution.
..87..
– 11. DATABASE CONCEPTS
3. Data:
It is the resource for which DBMS is designed. DBMS creation is to store and utilize
data.
4. Procedures/Methods:
They are general instructions to use a database management system such as
installation of DBMS, manage databases to take backups, report generation, etc.
5. DataBase Access Languages:
They are the languages used to write commands to access, insert, update and delete
data stored in any database.
30. Write about Database Structure.
➢ Table is the entire collection of related data in one table, referred to as a File or Table
where the data is organized as row and column.
➢ Each row in a table represents a record, which is a set of data for each database entry.
➢ Each table column represents a Field, which groups each piece or item of data among the
records into specific categories or types of data.
Eg. StuNo., StuName, StuAge, StuClass, StuSec.
o A Table is known as a RELATION
o A Row is known as a TUPLE
o A column is known as an ATTRIBUTE

..88..
12 STRUCTURED QUERY LANGUAGE

Part - I
Choose the best answer: (1 Mark)
1. Which commands provide definitions for creating table structure, deleting relations, and
modifying relation schemas.
(A) DDL (B) DML (C) DCL (D) DQL
2. Which command lets to change the structure of the table?
(A) SELECT (B) ORDER BY (C) MODIFY (D) ALTER
3. The command to delete a table is
(A) DROP (B) DELETE
(C) DELETE ALL (D) ALTER TABLE
4. Queries can be generated using
(A) SELECT (B) ORDER BY (C) MODIFY (D) ALTER
5. The clause used to sort data in a database
(A) SORT BY (B) ORDER BY (C) GROUP BY (D) SELECT
Part - II
Answer the following questions: (2 Marks)
1. Write a query that selects all students whose age is less than 18 in order wise.
SELECT * FROM student WHERE age<18 ORDER BY name;
2. Differentiate Unique and Primary Key constraint.
Unique Constraint Primary Key Constraint
It ensures that no two rows have the same It declares a field as a Primary key which
value in the specified columns. helps to uniquely identify a record.
More than one fields of a table can be set as Only one field of a table can be set as
primary key. primary key.
3. Write the difference between table constraint and column constraint?
➢ Table constraint: Table constraint apply to a group of one or more columns.
➢ Column constraint: Column constraint apply only to individual column.
4. Which component of SQL lets insert values in tables and which lets to create a table?
➢ DDL (Data Definition Language) – to create tables
➢ DML (Data Manipulation Language) – to insert values
5. What is the difference between SQL and MySQL?
❖ SQL : Structured Query Language is a language used for accessing database.
❖ MySQL : MySQL is a Database Management System like SQL Server, Oracle. MySQL is a
RDBMS.
Part - III
Answer the following questions: (3 Marks)
1. What is a constraint? Write short note on Primary key constraint.
Constraint is a condition applicable on a field or set of fields.

..89..
– 12. STRUCTURED QUERY LANGUAGE
Primary Key Constraint:
This constraint declares a field as a Primary key which helps to uniquely identify a record.
It is similar to unique constraint except that only one field of a table can be set as primary key.
The primary key does not allow NULL values.
2. Write a SQL statement to modify the student table structure by adding a new field.
ALTER TABLE student ADD address char(50);
3. Write any three DDL commands.
➢ Create: To create tables in the database.
➢ Alter: Alters the structure of the database.
➢ Drop: Delete tables from database.
➢ Truncate: Remove all records from a table, also release the space occupied by those
records.
4. Write the use of Savepoint command with an example.
➢ The SAVEPOINT command is used to temporarily save a transaction so that you can
rollback to the point whenever required.
➢ The different states of our table can be saved at anytime using different names and the
rollback to that state can be done using the ROLLBACK command.
Syntax:
SAVEPOINT savepoint_name;
Example:
Admno Name Age
105 Sumitha 21
106 Selvam 48
107 Aakash 14
UPDATE Student SET Name = ‘Mini’ WHERE Admno=105;
SAVEPOINT A;
SELECT * FROM STUDENT;
Admno Name Age
105 Mini 21
106 Selvam 48
107 Aakash 14
ROLLBACK TO A;
SELECT * FROM STUDENT;
Admno Name Age
105 Sumitha 21
106 Selvam 48
107 Aakash 14
5. Write a SQL statement using DISTINCT keyword.
➢ The DISTINCT keyword is used along with the SELECT command to eliminate duplicate
rows in the table.

..90..
– 12. STRUCTURED QUERY LANGUAGE
➢ This helps to eliminate redundant data.
For Example:
Admno Name Age Place SELECT ISTINCT Place FROM Student;
105 Sumitha 21 Madurai will display the following data:
106 Selvam 48 Chennai Place
107 Aakash 14 Chennai Madurai
108 Aruna 36 Coimbatore Chennai
109 Madhan 19 Madurai Coimbatore
Part - IV
Answer the following questions: (5 Marks)
1. Write the different types of constraints and their functions.
Constraints ensure database integrity, therefore known as database integrity constraints.
The different types of constraints are as follows
(i) Unique Constraint:
➢ This constraint ensures that no two rows have the same value in the specified
columns.
➢ For example, UNIQUE constraint applied on Admno of student table ensures that no
two students have the same admission number and the constraint can be used as:
CREATE TABLE Student
(
Admno integer NOT NULL UNIQUE, → Unique constraint
Name char (20) NOT NULL
);
(ii) Primary Key Constraint:
➢ This constraint declares a field as a Primary key which helps to uniquely identify a
record.
➢ It is similar to unique constraint except that only one field of a table can be set as
primary key. The primary key does not allow NULL values.
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint
Name char(20)NOT NULL
);
(iii) DEFAULT Constraint:
➢ The DEFAULT constraint is used to assign a default value for the field.
➢ When no value is given for the specified field having DEFAULT constraint,
automatically the default value will be assigned to the field.
(iv) Check Constraint:
➢ This constraint helps to set a limit value placed for a field. When we define a check
constraint on a single column, it allows only the restricted values on that field.
..91..
– 12. STRUCTURED QUERY LANGUAGE
(v) TABLE Constraint:
➢ When the constraint is applied to a group of fields of the table, it is known as Table
constraint.
➢ The table constraint is normally given at the end of the table definition.
CREATE TABLE Student
(
Admno integer NOT NULL,
Firstname char(20),
Lastname char(20),
Gender char(1) DEFAULT=’M’, → Default constraint
Age integer CHECK (Age <= 19), → Check constraint
PRIMARY KEY (Firstname, Lastname) → Table constraint
);
2. Consider the following employee table. Write SQL commands for the questions. (i)
to (v).

EMP CODE NAME DESIG PAY ALLO WANCE


S1001 Hariharan Supervisor 29000 12000
P1002 Shaji Operator 10000 5500
P1003 Prasad Operator 12000 6500
C1004 Manjima Clerk 8000 4500
M1005 Ratheesh Mechanic 20000 7000
(i) To display the details of all employees in descending order of pay.
(ii) To display all employees whose allowance is between 5000 and 7000.
(iii) To remove the employees who are mechanic.
(iv) To add a new row.
(v) To display the details of all employees who are operators.
SQL COMMANDS:
(i) SELECT * FROM EMPLOYEE ORDER BY PAY DESC;
(ii) SELECT * FROM EMPLOYEE WHERE ALLOWANCE BETWEEN 5000 AND 7000;
(iii) DELETE FROM EMPLOYEE WHERE DESIG='MECHANIC';
(iv) INSERT INTO EMPLOYEE VALUES ('S1006', 'RAJESH', 'MECHANIC', 20000, 7000);
(v) SELECT * FROM EMPLOYEE WHERE DESIG='OPERATOR';
3. What are the components of SQL? Write the commands in each.
i. DML - Data Manipulation Language
ii. DDL - Data Definition Language
iii. DCL - Data Control Language
iv. TCL - Transaction Control Language
v. DQL - Data Query Language

..92..
– 12. STRUCTURED QUERY LANGUAGE
(i) DATA DEFINITION LANGUAGE
❖ The Data Definition Language (DDL) consist of SQL statements used to define the
database structure or schema.
❖ It simply deals with descriptions of the database schema and is used to create and
modify the structure of database objects in databases.
SQL commands which comes under Data Definition Language are:
➢ Create: To create tables in the database.
➢ Alter: Alters the structure of the database.
➢ Drop: Delete tables from database.
➢ Truncate: Remove all records from a table, also release the space occupied by those
records.
(ii) DATA MANIPULATION LANGUAGE
❖ A Data Manipulation Language (DML) is a query language used for adding (inserting),
removing (deleting), and modifying (updating) data in a database.
❖ In SQL, the data manipulation language comprises the SQL-data change statements,
which modify stored data but not the schema of the database table.
SQL commands which comes under Data Manipulation Language are:
➢ Insert: Inserts data into a table
➢ Update: Updates the existing data within a table.
➢ Delete: Deletes all records from a table, but not the space occupied by them.
(iii) DATA CONTROL LANGUAGE
❖ A Data Control Language (DCL) is a programming language used to control the access
of data stored in a database. It is used for controlling privileges in the database
(Authorization).
❖ The privileges are required for performing all the database operations such as
creating sequences, views of tables etc.
SQL commands which come under Data Control Language are:
➢ Grant: Grants permission to one or more users to perform specific tasks.
➢ Revoke: Withdraws the access permission given by the GRANT statement.
(iv) TRANSACTIONAL CONTROL LANGUAGE
Transactional control language (TCL) commands are used to manage transactions in
the database. These are used to manage the changes made to the data in a table by DML
statements.
SQL command which come under Transfer Control Language are:
➢ Commit: Saves any transaction into the database permanently.
➢ Roll back: restores the database to last commit state.
➢ Save point: temporarily save a transaction so that you can rollback.
(v) DATA QUERY LANGUAGE
The Data Query Language consist of commands used to query or retrieve data from a
database. One such SQL command in Data Query Language is
➢ Select: It displays the records from the table.
..93..
– 12. STRUCTURED QUERY LANGUAGE
4. Construct the following SQL statements in the student table.
(i) SELECT statement using GROUP BY clause.
(ii) SELECT statement using ORDER BY clause.
If the Student table has the following data:
Admno Name Gender Age Place
100 Ashish M 17 Chennai
101 Adarsh M 18 Delhi
102 Akshith M 17 Bangalore
103 Ayush M 18 Delhi
104 Abinandh M 18 Chennai
105 Revathi F 19 Chennai
106 Devika F 19 Bangalore
107 Hema F 17 Chennai
(i) SELECT statement using GROUP BY clause.
SELECT Gender FROM Student GROUP BY Gender;
(ii) SELECT statement using ORDER BY clause.
SELECT * FROM Student ORDER BY Name;
5. Write a SQL statement to create a table for employee having any five fields and create
a table constraint for the employee table.
CREATE TABLE EMPLOYEE
(
EMPCODE CHAR(20),
NAME CHAR(20),
DESIG VARCHAR(20),
PAY INTEGER,
ALLOWANCE INTEGER,
PRIMARY KEY(EMPCODE) → Table constraint
);
ADDITIONAL QUESTIONS
1. SQL stands for
a) Structured Question Language b) Structured Query Language
c) Standard Query Language d) Standard Question Language
2. The original version of SQL was developed at
a) ORACLE Corporation b) IBM’s Research Centre
c) Microsoft Corporation b) Google
3. SQL was originally called as
a) SQLite b) MySQL c) Sequel d) RSQL
4. The latest version of SQL was released in
a) 2018 b) 2004 c) 2006 d) 2008
5. A condition applicable on a field or set of fields is
a) Commands b) Clauses c) Constraint d) Keywords

..94..
– 12. STRUCTURED QUERY LANGUAGE
6. EDML stands for
a) Embedded Data Manipulation Language b) Essential Data Manipulation Language
c) Embedded Data Monitoring Language d) Embedded Data Manipulation Learning
7. Which constraint may use relational and logical operators for condition?
a) Check b) Unique c) Limit d) Assign
8. The constraint used to assign a default value for the field in table is
a) Assign b) Default c) Set d) Reset
9. Which keyword will display every row of the table without considering duplicate entries?
a) DISTINCT b) ALL c) DUPLICATE d) IN
10. Which command used to delete all the rows but it does not free the space containing the
table?
A) DELETE b) ERASE C) TRUNCATE d) DROP
11. Which command used to delete all the rows from the table, the structure remains and the
space is freed?
a) DELETE b) ERASE c) TRUNCATE d) DROP
12. Which keyword is used to sort the data in descending order?
a) ASC b) DSC c) DESC d) DASC
13. What is SQL?
➢ The Structured Query Language (SQL) is a standard programming language to create and
manipulate databases.
➢ SQL allows the user to create, retrieve, alter, and transfer information among databases.
14. What is CRUD?
In database, functions related to Create, Read, Update and Delete operations, collectively
known as CRUD.
15. What is database?
Database is a collection of tables that store sets of data that can be queried for use in
other applications.
16. What are field and record?
➢ A field is a column in a table that is designed to maintain specific related information
about every record in the table.
➢ A Record is a row, which is a collection of related fields or columns that exist in a table.
17. Write the procedure to create a new database.
1. To create a database, type the following command.
CREATE DATABASE database_name;
✓ For example, to create a database to store the tables:
CREATE DATABASE stud;
2. To work with the database, type the following command.
USE DATABASE;
✓ For example, to use the stud database created.
USE stud;

..95..
– 12. STRUCTURED QUERY LANGUAGE
18. What are the functions performed by DDL?
1. It should identify the type of data division such as data item, segment, record and
database file.
2. It gives a unique name to each data item type, record type, file type and data base.
3. It should specify the proper data type.
4. It should define the size of the data item.
5. It may define the range of values that a data item may use.
6. It may specify privacy locks for preventing unauthorized data entry.
19. Explain the two types of DML.
❖ Procedural DML – Requires a user to specify what data is needed and how to get it.
❖ Non-Procedural DML - Requires a user to specify what data is needed without specifying
how to get it.
20. Write the functions of SQL commands.
The SQL provides a predetermined set of commands to work on databases.
❖ Keywords They have a special meaning in SQL. They are understood as instructions.
❖ Commands They are instructions given by the user to the database also known as
statements.
❖ Clauses They begin with a keyword and consist of keyword and argument.
❖ Arguments They are the values given to make the clause complete.
21. Write the different types of constraints.
 Unique constraint  Primary Key constraint
 Default constraint  Check constraint
22. What is the use of default constraint?
➢ The DEFAULT constraint is used to assign a default value for the field.
➢ When no value is given for the specified field having DEFAULT constraint, automatically
the default value will be assigned to the field.
Example:
CREATE TABLE Student (
Name char(20)NOT NULL,
Age integer DEFAULT = “17”, );
✓ In the above example the “Age” field is assigned a default value of 17, therefore
when no value is entered in age by the user, it automatically assigns 17 to Age.
23. What is the use of check constraint?
➢ This constraint helps to set a limit value placed for a field.
➢ When we define a check constraint on a single column, it allows only the restricted values
on that field.
Example:
CREATE TABLE Student (
Name char(20)NOT NULL,
Age integer CHECK (Age <=19));

..96..
– 12. STRUCTURED QUERY LANGUAGE
✓ In the above example the check constraint is set to Age field where the value of
Age must be less than or equal to 19.
24. Differentiate TRUNCATE and DROP TABLE.
TRUNCATE DROP TABLE
The TRUNCATE command is used to delete The DROP command is used to remove an
all the rows. object from the database. If you drop a
table, all the rows in the table are deleted.
The structure remains in the table and free The table structure is removed from the
the space containing the table. database. Once a table is dropped, we
cannot get it back.
Syntax: Syntax:
TRUNCATE TABLE table-name; DROP TABLE table-name;
25. Explain SELECT command.
➢ The SELECT command is used to query or retrieve data from a table in the database. It is
used to retrieve a subset of records from one or more tables.
➢ The SELECT command can be used in various forms.
Syntax:
SELECT <column-list> FROM <table-name>;
Example:
(1) For example to view only admission number and name of students from the Student
table the command is given as follows:
SELECT Admno, Name FROM Student;
(2) To view all the fields and rows of the table the SELECT command can be given as
SELECT * FROM STUDENT;
26. What are uses the of the keywords BETWEEN and NOT BETWEEN?
➢ The BETWEEN keyword defines a range of values the record must fall into to make the
condition true.
➢ The range may include an upper value and a lower value between which the criteria must
fall into.
SELECT Admno, Name, Age FROM Student WHERE Age BETWEEN 18 AND 19;
➢ The NOT BETWEEN is reverse of the BETWEEN operator where the records not satisfying
the condition are displayed.
SELECT Admno, Name, Age FROM Student WHERE Age NOT BETWEEN 18 AND 19;
27. Write about the keywords IN and NOT IN?
➢ The IN keyword is used to specify a list of values which must be matched with the record
values.
➢ In other words, it is used to compare a column with more than one value. It is similar to
an OR condition.
For Example:
SELECT Admno, Name, Place FROM Student WHERE Place IN (‘Chennai’, ‘Delhi’);

..97..
– 12. STRUCTURED QUERY LANGUAGE
➢ The NOT IN keyword displays only those records that do not match in the list.
For example:
SELECT Admno, Name, Place FROM Student WHERE Place NOT IN (‘Chennai’, ‘Delhi’);
✓ will display students only from places other than “Chennai” and “Delhi”
28. How can you search a NULL value field?
➢ The NULL value in a field can be searched in a table using the IS NULL in the WHERE clause.
➢ For example, to list all the students whose Age contains no value, the command is used
as:
SELECT * FROM Student WHERE Age IS NULL;
29. Write about COMMIT.
➢ The COMMIT command is used to permanently save any transaction to the database.
Once the COMMIT command is given, the changes made cannot be rolled back.
The COMMIT command is used as
COMMIT;
30. Write about ROLLBACK.
➢ The ROLLBACK command restores the database to the last commited state. It is used with
SAVEPOINT command to jump to a particular savepoint location.
Syntax:
ROLL BACK TO save point name;
31. Explain the processing skills of SQL.
1. Data Definition Language (DDL):
The SQL DDL provides commands for defining relation schemas (structure), deleting
relations, creating indexes and modifying relation schemas.
2. Data Manipulation Language (DML):
The SQL DML includes commands to insert, delete, and modify tuples in the database.
3. Embedded Data Manipulation Language:
The embedded form of SQL is used in high level programming languages.
4. View Definition:
The SQL also includes commands for defining views of tables.
5. Authorization:
The SQL includes commands for access rights to relations and views of tables.
6. Integrity:
The SQL provides forms for integrity checking using condition.
7. Transaction control:
The SQL includes commands for file transactions and control over transaction
processing.
32. Tabulate the different data types in a database.
Data Type Description
char Fixed width string value. Values of this type is enclosed in single
(character) quotes.

..98..
– 12. STRUCTURED QUERY LANGUAGE
varchar Variable width character string. This is similar to char except the
size of the data entry vary considerably.
dec It represents a fractional number such as 15.12, 0.123 etc. Here
(Decimal) the size argument consists of two parts : precision and scale. The
size (5, 2) indicates precision as 5 and scale as 2.
numeric It is same as decimal except that the maximum number of digits
may not exceed the precision argument.
int ) It represents a number without a decimal point. Here the size
(Integer) argument is not used.
smallint It is same as integer but the default size may be smaller than
Integer.
float It represents a floating-point number in base 10 exponential
notation and may define a precision up to a maximum of 64.
real It is same as float, except the size argument is not used and may
define a precision up to a maximum of 64.
double Same as real except the precision may exceed 64.
33. Explain the different DML commands.
Once the schema or structure of the table is created, values can be added to the table.
The DML commands consist of inserting, deleting and updating rows into the table.
(1) INSERT command:
❖ The INSERT command helps to add new data to the database or add new records to
the table.
The command is used as follows:
INSERT INTO [column-list] VALUES (values);
Example:
INSERT INTO Student (Admno, Name, Gender, Age, Place)
VALUES (100, ‘Ashish’, ‘M’, 17, ‘Chennai’);
(2) DELETE command:
❖ The DELETE command permanently removes one or more records from the table. It
removes the entire row, not individual fields of the row, so no field argument is
needed.
The DELETE command is used as follows:
DELETE FROM table-name WHERE condition;
✓ For example, to delete the record whose admission number is 104 the command
is given as follows:
DELETE FROM Student WHERE Admno=104;
✓ To delete all the rows of the table, the command is used as:
DELETE FROM Student;

..99..
– 12. STRUCTURED QUERY LANGUAGE
(3) UPDATE command:
❖ The UPDATE command updates some or all data values in a database. It can update
one or more records in a table. The UPDATE command specifies the rows to be
changed using the WHERE clause and the new data using the SET keyword.
The command is used as follows:
UPDATE SET column-name = value, column-name = value,… WHERE condition;
❖ Example:
UPDATE Student SET Age = 20 WHERE Place = ‘Bangalore’;
✓ The above command will change the age to 20 for those students whose place
is “Bangalore”.
34. Explain the use of ALTER command.
The ALTER command is used to alter the table structure like adding a column, renaming
the existing column, change the data type of any column or size of the column or delete the
column from the table.
It is used in the following way:
(1) Command for inserting columns in table format:
ALTER TABLE <table-name> ADD <column-name><data type><size>;
Example:
✓ To add a new column “Address” of type ‘char’ to the Student table, the command
is used as
ALTER TABLE Student ADD Address char;
(2) Command for modifying an existing column in the table:
ALTER TABLE <table-name> MODIFY<column-name><data type><size>;
Example:
ALTER TABLE Student MODIFY Address char (25);
✓ The above command will modify the address column of the Student table to now
hold 25 characters.
(3) Command for renaming existing column:
ALTER TABLE <table-name> CHANGE
old-column-name new-column-name, new coloum definition;
For example, to rename the column Address to City, the command is used as:
ALTER TABLE Student CHANGE Address City char(20);
(4) The command to remove a column or all columns:
ALTER TABLE <table-name> DROP COLUMN <column-name>;
For example, to remove the column City from the Student table, the command is
used as:
ALTER TABLE Student DROP COLUMN City;
(The above can be asked in two or three marks compulsory questions)

..100..
13 PYTHON AND CSV FILES

Part - I
Choose the best answer: (1 Mark)
1. A CSV file is also known as a ….
(A) Flat File (B) 3D File (C) String File (D) Random File
2. The expansion of CRLF is
(A) Control Return and Line Feed (B) Carriage Return and Form Feed
(C) Control Router and Line Feed (D) Carriage Return and Line Feed
3. Which of the following module is provided by Python to do several operations on the CSV
files?
(A) py (B) xls (C) csv (D) os
4. Which of the following mode is used when dealing with non-text files like image or exe files?
(A) Text mode (B) Binary mode (C) xls mode (D) csv mode 5
5. The command used to skip a row in a CSV file is
(A) next() (B) skip() (C) omit() (D) bounce()
6. Which of the following is a string used to terminate lines produced by writer()method of csv
module?
(A) Line Terminator (B) Enter key (C) Form feed (D) Data Terminator
7. What is the output of the following program? import csv
d=csv.reader(open('c:\PYPRG\ch13\city.csv'))
next(d)
for row in d:
print(row)
if the file called “city.csv” contain the following details
chennai, mylapore
mumbai, andheri
A) chennai,mylapore (B) mumbai,andheri
(C) chennai (D) chennai,mylapore
mumba mumbai,andheri
8. Which of the following creates an object which maps data to a dictionary?
(A) listreader() (B) reader() (C) tuplereader() (D) DictReader()
9. Making some changes in the data of the existing file or adding more data is called
(A) Editing (B) Appending (C) Modification (D) Alteration
10. What will be written inside the file test.csv using the following program
import csv (A) Exam Quarterly Halfyearly
D = [['Exam'],['Quarterly'],['Halfyearly']] (B) Exam Quarterly Halfyearly
csv.register_dialect('M',lineterminator = '\n') (C) E (D) Exam,
with open('c:\pyprg\ch13\line2.csv', 'w') as f: Q Quarterly,
wr = csv.writer(f,dialect='M') H Halfyearly
wr.writerows(D)
f.close()

..101..
– 13. PYTHON AND CSV FILES
Part - II
Answer the following questions: (2 Marks)
1. What is CSV File?
A CSV file is a human readable text file where each line has a number of fields, separated
by commas or some other delimiter.
2. Mention the two ways to read a CSV file using Python.
1. Use the csv module’s reader function
2. Use the DictReader class.
3. Mention the default modes of the File.
The following are the default modes of the file.
(ii) 'r' Open a file for reading. (default)
(iii) 't' Open in text mode. (default)
4. What is use of next() function?
The next() function returns the next item from the iterator. It can also be used to skip a
row of the csv file.
5. How will you sort more than one column from a csv file? Give an example statement.
To sort by more than one column you can use itemgetter with multiple indices:
operator.itemgetter (1, 2)
Example:
Consider test.csv file:
name,age
Nandhini,20
Mathu,20
Nikhil,19
Code for multiple sort:
import csv, operator
data = csv.reader(open(‘d:\\test.csv’))
next(data)
sortedlist=sorted(data, key=operator.itemgetter(age, name))
for row in sorterdlist:
print(row)
Output:
[19,Nikhil]
[20,Mathu]
[20,Nandhini]
Part - III
Answer the following questions: (3 Marks)
1. Write a note on open() function of python. What is the difference between the two
methods?
Python has a built-in function open() to open a file. This function returns a file object, also
called a handle, as it is used to read or modify the file accordingly.
..102..
– 13. PYTHON AND CSV FILES
The two different methods are
(i) open("sample.txt") as f:
(ii) with open()
The open() method is not entirely safe. If an exception occurs when you are performing
some operation with the file, the code exits without closing the file.
But “with open” statement ensures that the file is closed when the block inside with is
exited.
2. Write a Python program to modify an existing file.
The “student.csv” file contains the following data.
Roll No Name City
1 Harshini Chennai
2 Adhith Mumbai
3 Dhuruv Bengaluru
The following program modifying the value of an existing row in student.csv
import csv
row = [‘2’, ‘Meena’,’Bangalore’]
with open(‘student.csv’, ‘r’) as readFile:
reader = csv.reader(readFile)
lines = list(reader)
lines[2] = row
with open(‘student.csv’, ‘w’) as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)
readFile.close()
writeFile.close()
When we open the student.csv file with text editor, then it will show:
Roll No Name City
1 Harshini Chennai
2 Meena Bangalore
3 Dhuruv Bengaluru
3. Write a Python program to read a CSV file with default delimiter comma (,).
import csv
with open(‘student.csv’,'r') as readFile:
reader=csv.reader(readFile)
for row in reader:
print(row)
readFile.close( )
4. What is the difference between the write mode and append mode.
‘w’ - write mode:
Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.

..103..
– 13. PYTHON AND CSV FILES
‘a’ – append mode:
Open for appending at the end of the file without truncating it. Creates a new file if it
does not exist.
5. What is the difference between reader() method and DictReader() class?
reader() DictReader()
The reader function is designed to take each DictReader() creates an object which maps
line of the file and make a list of all columns. data to a dictionary.
csv.reader() works with list/tuple. csv.DictReader() works with dictionary
Part - IV
Answer the following questions: (5 Marks)
1. Differentiate Excel file and CSV file.
Excel CSV
Excel is a binary file that holds information CSV format is a plain text format with a
about all the worksheets in a file, including series of values separated by commas.
both content and formatting.
XLS files can only be read by applications CSV can be opened with any text editor in
that have been especially written to read Windows like notepad, MS Excel,
their format, and can only be written in the OpenOffice, etc.
same way.
Excel is a spreadsheet that saves files with CSV is a format for saving tabular
the extension “.xls” or “.xlsx” information into a delimited text file with
extension “.csv”
Excel consumes more memory while Importing CSV files can be much faster, and
importing data. it also consumes less memory.
2. Tabulate the different file modes with its meaning.
Mode Description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the
file if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
'a' Open for appending at the end of the file without truncating it. Creates a
new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a file for updating (reading and writing)
3. Write the different methods to read a File in Python.
There are two ways to read a CSV file.
1. Use the csv module’s reader function
2. Use the DictReader class.

..104..
– 13. PYTHON AND CSV FILES
1. CSV Module’s Reader Function:
➢ The csv.reader() method is designed to take each line of the file and make a list of all
columns.
➢ Using this method one can read data from csv files of different formats like quotes
(" "), pipe (|) and comma (,).
The syntax for csv.reader() is
csv.reader(fileobject, delimiter, fmtparams)
where
✓ file object: passes the path and the mode of the file
✓ delimiter: an optional parameter containing the standard dialects like , | etc
can be omitted.
✓ fmtparams: optional parameter which help to override the default values of
the dialects like skip initial space, quoting etc. can be omitted.
Example:
import csv
with open(‘Student.csv’,'r') as readFile:
reader=csv.reader(readFile)
for row in reader:
print(row)
readFile.close( )
2. Reading CSV File into A Dictionary:
➢ To read a CSV file into a dictionary can be done by using DictReader which creates an
object which maps data to a dictionary.
➢ DictReader works by reading the first line of the CSV and using each comma separated
value in this line as a dictionary key.
➢ The columns in each subsequent row then behave like dictionary values and can be
accessed with the appropriate key.
Example:
import csv
filename="Student.csv"
myfile=csv.DictReader(open(‘Student.csv’,‘r‘))
for row in myfile:
print(dict(row))
4. Write a Python program to write a CSV File with custom quotes.
import csv
csvData = [[‘SNO’,’Items’], [‘1’,’Pen’], [‘2’,’Book’], [‘3’,’Pencil’]]
csv.register_dialect(‘myDialect’,delimiter=‘|’,quotechar = ‘”’, quoting=csv.QUOTE_ALL)
with open(‘c:\pyprg\ch13\quote.csv’, ‘w’) as csvFile:
writer = csv.writer(csvFile, dialect=’myDialect’)
writer.writerows(csvData)
print(“writing completed”)
csvFile.close()

..105..
– 13. PYTHON AND CSV FILES
5. Write the rules to be followed to format the data in a CSV file.
1. Each record (row of data) is to be located on a separate line, delimited by a line break by
pressing enter key. For example: 
xxx,yyy  ( denotes enter Key to be pressed)
2. The last record in the file may or may not have an ending line break. For example:
ppp, qqq 
yyy, xxx
3. There may be an optional header line appearing as the first line of the file with the same
format as normal record lines. For example:
field_name1,field_name2,field_name3 
aaa,bbb,ccc 
zzz,yyy,xxx CRLF (Carriage Return and Line Feed)
4. Within the header and each record, there may be one or more fields, separated by
commas. Spaces are considered part of a field and should not be ignored. The last field in
the record must not be followed by a comma. For example:
Red , Blue
5. Each field may or may not be enclosed in double quotes. If fields are not enclosed with
double quotes, then double quotes may not appear inside the fields. For example:
"Red","Blue","Green"  #Field data with doule quotes
Black,White,Yellow #Field data without doule quotes
6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in
double-quotes. For example:
Red, “,”, Blue CRLF
Red, Blue , Green
7. If double-quotes are used to enclose fields, then a double-quote appearing inside a field
must be preceded with another double quote. For example:
“Red, ” “Blue”, “Green”,
, , White
ADDITIONAL QUESTIONS
1. Expansion of CSV
a) Common Separated Values b) Colon Separated Values
c) Condition Separated Values d) Comma Separated Values
2. Files saved in ________ cannot be opened or edited by text editors.
a) CSV b) EXCEL c) PYTHON d) C++
3. If the fields of data in your CSV file contain commas, you can protect them by enclosing those
data fields in ________
a) slash (/) b) double-quote(“) c) colon (:) d) semi-colon (;)
4. In Python, if no mode is specified the default mode _______ is used
a) a b) w c) rt d) b
5. Which file mode is used to open for appending at the end of the file without truncating it?
a) a b) w c) rt d) b
..106..
– 13. PYTHON AND CSV FILES
6. Which file mode is used to open in binary mode?
a) a b) w c) rt d) b
7. Which file mode is used to Open a file for updating (reading and writing)?
a) a b) w c) rt d) +
8. Which method will free up the resources that were tied with the file?
a) remove() b) delete() c) release() d) close()
9. A class of CSV module which helps to define parameters for reading and writing CSV is
a) reader() b) dialect c) writer() d) close()
10. The parameter used to remove whitespaces after the delimiter is
a) removespace b) delspace c) skipinitialspace d) delimiter
11. Which of the following method takes 1-dimensional data (one row) to write in a file?
a) write() b) writerow() c) writer() d) writerows()
12. Which of the following method takes 2-dimensional data (multiple rows) to write in a file?
a) write() b) writerow() c) writer() d) writerows()
13. The default value for Line terminator is
a) \n b) \r c) \l d) \n or \r
14. Write the purpose of CSV file.
➢ CSV is a simple file format used to store tabular data, such as a spreadsheet or database.
➢ Since they're plain text, they're easier to import into a spreadsheet or another storage
database, regardless of the specific software you're using.
➢ You can open CSV files in a spreadsheet program like Microsoft Excel or in a text
editor or through a database which make them easier to read.
15. How will you create a new CSV file using Microsoft Excel?
❖ To create a CSV file using Microsoft Excel, launch Excel and then open the file you want
to save in CSV format.
❖ Once the data is entered in the worksheet, select File → Save As option, and for the “Save
as type option”, select CSV (Comma delimited) or type the file name along with extension
.csv.
16. Write the procedure to open CSV file in MS Excel.
i. If Microsoft Excel has been installed on the computer, by default CSV files should open
automatically in Excel when the file is double-clicked.
ii. Select File → Open from the Microsoft Excel, and select the CSV file.
17. What is Dialect?
Dialect is a class of csv module which helps to define parameters for reading and writing
CSV. It allows you to create, store, and re-use various formatting parameters for your data.
18. What is the difference between writerow() and writerows() functions?
➢ The writerow() method writes one row at a time.
➢ writerows() method writes all the data at once.

..107..
14 IMPORTING C++ PROGRAMS IN PYTHON

Part - I
Choose the best answer: (1 Mark)
1. Which of the following is not a scripting language?
(A) JavaScript (B) PHP (C) Perl (D) HTML
2. Importing C++ program in a Python program is called
(A) wrapping (B) Downloading (C) Interconnecting (D) Parsing
3. The expansion of API is
(A) Application Programming Interpreter
(B) Application Programming Interface
(C) Application Performing Interface
(D) Application Programming Interlink
4. A framework for interfacing Python and C++ is
(A) Ctypes (B) SWIG (C) Cython (D) Boost
5. Which of the following is a software design technique to split your code into separate parts?
(A) Object oriented Programming
(B) Modular programming
(C) Low Level Programming
(D) Procedure oriented Programming
6. The module which allows you to interface with the Windows operating system is
(A) OS module (B) sys module (c) csv module (d) getopt module
7. getopt() will return an empty array if there is no error in splitting strings to
(A) argv variable (B) opt variable (c) args variable (d) ifile variable
8. Identify the function call statement in the following snippet.
if __name__ =='__main__':
main(sys.argv[1:])
(A) main(sys.argv[1:]) (B) __name__ (C) __main__ (D) argv
9. Which of the following can be used for processing text, numbers, images, and scientific data?
(A) HTML (B) C (C) C++ (D) PYTHON
10. What does __name__ contains?
(A) c++ filename (B) main() name
(C) python filename (D) os module name
Part - II
Answer the following questions: (2 Marks)
1. What is the theoretical difference between Scripting language and other programming
language?
➢ The theoretical difference between the two is that scripting languages do not require the
compilation step and are rather interpreted.
➢ A scripting language requires an interpreter while a programming language requires a
compiler.

..108..
– 14. IMPORTING C++ PROGRAMS IN PYTHON
2. Differentiate compiler and interpreter.
Compiler Interpreter
Scans the entire program and translates it as Translates program one statement at a
a whole into machine code. time.
It generates the error message only after It continues translating the program until
scanning the whole program. the first error is met, in which case it stops.
Debugging is comparatively hard. Debugging is easy.
3. Write the expansion of (i) SWIG (ii)MinGW
(i) SWIG - Simplified Wrapper Interface Generator
(ii) MinGW - Minimalist GNU for Windows
4. What is the use of modules?
➢ We use modules to break down large programs into small manageable and organized
program.
➢ Furthermore, modules provide reusability of code.
➢ We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
5. What is the use of cd command? Give an example.
➢ cd command refers to change directory.
➢ In this Example, the prompt shows the "C:\>”. To goto the directory “pyprg”, type the
command 'cd pyprg' in the command prompt.
➢ It changes to “c:\pyprg>”
Part - III
Answer the following questions: (3 Marks)
1. Differentiate PYTHON and C++
PYTHON C++
Python is typically an "interpreted" C++ is typically a "compiled" language.
language.
Python is a dynamic-typed language. C++ is compiled statically typed language.
Data type is not required while declaring Data type is required while declaring
variable. variable.
It can act both as scripting and general- It is a general-purpose language.
purpose language.
2. What are the applications of scripting language?
1. To automate certain tasks in a program.
2. Extracting information from a data set.
3. Less code intensive as compared to traditional programming language.
4. can bring new functions to applications and glue complex systems together.
3. What is MinGW? What is its use?
➢ MinGW refers to a set of runtime header files, used in compiling and linking the code of
C, C++ and FORTRAN to be run on Windows Operating System.

..109..
– 14. IMPORTING C++ PROGRAMS IN PYTHON
➢ MinGW allows to compile and execute C++ program dynamically through Python program
using g++.
4. Identify the module, operator, definition name for the following
welcome.display()
Function call
Dot operator
Module Name
5. What is sys.argv? What does it contain?
➢ sys.argv is the list of command-line arguments passed to the Python program.
➢ argv contains all the items that come via the command-line input, it's basically a list
holding the command-line arguments of the program.
➢ The first argument, sys.argv[0] contains the name of the python program.
➢ sys.argv[1] is the next argument passed to the program.
Part - IV
Answer the following questions: (5 Marks)
1. Write any 5 features of Python.
❖ Python uses Automatic Garbage Collection whereas C++ does not.
❖ C++ is a statically typed language, while Python is a dynamically typed language.
❖ Python runs through an interpreter, while C++ is pre-compiled.
❖ Python code tends to be 5 to 10 times shorter than that written in C++.
❖ In Python, there is no need to declare types explicitly where as it should be done in C++.
❖ In Python, a function may accept an argument of any type, and return multiple values
without any kind of declaration beforehand. Whereas in C++ return statement can return
only one value.
2. Explain each word of the following command.
python <filename.py> -<i> <C++ filename without cpp extension>
✓ python - keyword to execute the Python program from command line
✓ filename.py - Name of the Python program to executed
✓ -i - input mode
✓ C++ filename without cpp extension - name of C++ file to be compiled and executed.
3. What is the purpose of sys, os, getopt module in Python. Explain.
Python’s sys module:
This module provides access to built-in variables used by the interpreter. One among the
variable in sys module is argv.
sys.argv:
➢ sys.argv is the list of command-line arguments passed to the Python program.
➢ argv contains all the items that come via the command-line input, it's basically a list
holding the command-line arguments of the program.
➢ The first argument, sys.argv[0] contains the name of the python program.
➢ sys.argv[1] is the next argument passed to the program.

..110..
– 14. IMPORTING C++ PROGRAMS IN PYTHON
Python's OS Module:
➢ The OS module in Python provides a way of using operating system dependent
functionality.
➢ The functions that the OS module allows you to interface with the Windows operating
system where Python is running on.
➢ Execute the C++ compiling command in the shell. For Example, to compile C++ program
g++ compiler should be invoked through the following command
os.system (‘g++ ’ + <variable_name1> ‘ -<mode> ’ + <variable_name2>
Python getopt module:
➢ The getopt module of Python helps you to parse (split) command-line options and
arguments.
➢ This module provides getopt() method to enable command-line argument parsing.
getopt.getopt function:
This function parses command-line options and parameter list. Following is the syntax for
this method
<opts>,<args>=getopt.getopt(argv, options, [long_options])
4. Write the syntax for getopt() and explain its arguments and return values.
This function parses command-line options and parameter list.
Syntax:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
Here,
✓ argv − This is the argument list of values to be parsed (splited)
✓ options − This is string of option letters that the Python program recognize as, for
input or for output, with options (like ‘i’ or ‘o’) that followed by a colon (:). Here colon
is used to denote the mode.
✓ long_options −This contains a list of strings. Argument of Long options should be
followed by an equal sign ('=').
✓ getopt() method returns value consisting of two elements. Each of these values are
stored separately in two different list (arrays) opts and args.
✓ opts contains list of splitted strings like mode and path.
✓ args contains error string, if at all the comment is given with wrong path or mode.
args will be an empty list if there is no error.
5. Write a Python program to execute the following c++ coding.
#include <iostream>
using namespace std;
int main()
{ cout<<“WELCOME”;
return(0);
}
The above C++ program is saved in a file “welcome.cpp”

..111..
– 14. IMPORTING C++ PROGRAMS IN PYTHON
Python Program:
# Save the following python programs as “myprg.py”
import sys, os, getopt
def main(argv):
opts, args = getopt.getopt(argv, "i:")
for o, a in opts:
if o in "-i":
run(a)
def run(a):
inp_file=a+'.cpp'
exe_file=a+'.exe'
os.system('g++ ' + inp_file + ' -o ' + exe_file)
os.system(exe_file)
if __name__=='__main__':
main(sys.argv[1:])
ADDITIONAL QUESTIONS
1. In which language data type is not required while declaring variable?
a) Python b) java c) C++ d) All of these
2. A framework for interfacing C and C++ is
a) Ctypes b) SWIG c) Cython d) Boost
3. Expansion of MinGW is
a) Minimalist Graphics for Windows b) Minimalist GNU for Windows
c) Minimum Graphics for Windows d) Minimum GNU for Windows
4. Expansion of SWIG is
a) Simplified Wrapper Information Generator b) Software Wrapper Interface
Generator
c) Software Wrapper Information Generator
d) Simplified Wrapper Interface Generator
5. It is not an interface of C language?
a) Ctypes b) PythonC API c) Boost d) Cython
6. Which of the following is a scripting language?
a) HTML b) Ruby c) JAVA d) C++
7. To clear the screen in command window use
a) clear b) clrscr c) cls d) clean
8. Which keyword is used to import the definitions inside a module to another module?
a) import b) getopt c) sys d) os
9. Which of the following is not a module in Python?
a) sys b) getopt c) argv d) os
10. The list of command-line arguments passes to the Python program is
a) sys b) getopt c) argv d) sys.argv

..112..
– 14. IMPORTING C++ PROGRAMS IN PYTHON
11. A module of Python helps you to parse(split) command-line options and arguments is
a) OS b) getopt c) argv d) sys
12. A special variable by default stores the name of the file is
a) __main__ b) __name__ c) __sys__ d) __getopt__
13. Write short note on Scripting Language.
➢ A scripting language is a programming language designed for integrating and
communicating with other programming languages.
➢ Since a scripting language is normally used in conjunction with another programming
language, they are often found alongside HTML, Java or C++.
14. List some scripting languages.
 JavaScript  VBScript  PHP  Perl
 Python  Ruby  ASP and  Tcl
15. What is Garbage Collection?
Python deletes unwanted objects (built-in types or class instances) automatically to free
the memory space. The process by which Python periodically frees and reclaims blocks of
memory that no longer are in use is called Garbage Collection.
16. Name some of the commonly used interfaces to import C++ files in Python.
 Python-C-API  Ctypes  SWIG
 Cython  Boost. Python  MinGW
17. What is g++?
➢ g++ is a program that calls GCC (GNU C Compiler) and automatically links the required C++
library files to the object code.
➢ MinGW allows to compile and execute C++ program dynamically through Python program
using g++.
18. Explain __name__ (A Special variable) in Python.
➢ There is no main() function in Python, when the command to run a Python program is
given to the interpreter, the code that is at level 0 indentation is to be executed.
➢ However, before doing that, interpreter will define a few special variables. __name__ is
one such special variable which by default stores the name of the file.
➢ If the source file is executed as the main program, the interpreter sets the __name__
variable to have the name of the source file as its value.
➢ “__main__” by defaut contains the name of the source file (Python program)
➢ __name__ is a built-in variable which evaluates to the name of the current module.
Thus it can be used to check whether the current script is being run on its own.
For example:
if __name__ == '__main__':
main (sys.argv[1:])
✓ __main__ contains the name of that Python program and the Python special variable
__name__ also contain the Python program name.
✓ If the condition is true it calls the main which is passed with C++ file as argument.

..113..
15 DATA MANIPULATION THROUGH SQL

Part - I
Choose the best answer: (1 Mark)
1. Which of the following is an organized collection of data?
(A) Database (B) DBMS (C) Information (D) Records
2. SQLite falls under which database system?
(A) Flat file database system (B) Relational Database system
(C) Hierarchical database system (D) Object oriented Database system
3. Which of the following is a control structure used to traverse and fetch the records of the
database?
(A) Pointer (B) Key (C) Cursor (D) Insertion point
4. Any changes made in the values of the record should be saved by the command
(A) Save (B) Save As (C) Commit (D) Oblige
5. Which of the following executes the SQL command to perform some action?
(A) execute() (B) key() (C) cursor() (D) run()
6. Which of the following function retrieves the average of a selected column of rows in a table?
(A) Add() (B) SUM() (C) AVG() (D) AVERAGE()
7. The function that returns the largest value of the selected column is
(A) MAX() (B) LARGE() (C) HIGH() (D)MAXIMUM()
8. Which of the following is called the master table?
(A) sqlite_master (B) sql_master
(C) main_master (D) master_main
9. The most commonly used statement in SQL is
(A) cursor (B) select (C) execute (D) commit
10. Which of the following keyword avoid the duplicate?
(A) Distinct (B) Remove (C) Where (D) GroupBy
Part - II
Answer the following questions: (2 Marks)
1. Mention the users who uses the Database.
Users of database can be human users, other programs or applications.
2. Which method is used to connect a database? Give an example.
To connect SQLite database,
Step1: import sqlite3
Step2: create a connection using connect () method and pass the name of the database File
Step3: Set the cursor object cursor = connection. cursor()
Example:
import sqlite3
connection = sqlite3.connect ("Academy.db")
cursor = connection.cursor()

..114..
– 15. DATA MANIPULATION THROUGH SQL
3. What is the advantage of declaring a column as “INTEGER PRIMARY KEY”?
If a column of a table is declared to be an INTEGER PRIMARY KEY, then
✓ whenever a NULL will be used as an input for this column, the NULL will be automatically
converted into an integer which will one larger than the highest value so far used in that
column.
✓ If the table is empty, the value 1 will be used.
4. Write the command to populate record in a table. Give an example.
To populate (add record) the table "INSERT" command is passed to SQLite. “execute”
method executes the SQL command to perform some action.
Example:
cursor.execute(“””INSERT INTO Student (Rollno, Sname) VALUES (1561, "Aravind")”””)
5. Which method is used to fetch all rows from the database table?
➢ cursor.fetchall() -fetchall () method is to fetch all rows from the database table.
Example:
cursor.execute("SELECT * FROM student")
print(cursor.fetchall())
Part - III
Answer the following questions: (3 Marks)
1. What is SQLite? What is it advantage?
➢ SQLite is a simple relational database system, which saves its data in regular data files or
even in the internal memory of the computer.
Advantages:
➢ It is designed to be embedded in applications, instead of using a separate database server
program such as MySQL or Oracle.
➢ SQLite is fast, rigorously tested, and flexible, making it easier to work.
➢ Python has a native library for SQLite.
2. Mention the difference between fetchone() and fetchmany()
fetchone() fetchmany()
This method returns the next row of a query This method returns the next number of
result set or None in case there is no row left rows (n) of the result set.
It takes no argument. It takes one argument.
Example: Example:
res = cursor.fetchone() res = cursor.fetchmany(3)
3. What is the use of Where clause? Give a python statement using the where clause.
➢ The WHERE clause is used to extract only those records that fulfil a specified condition.
For example, to display the different grades scored by male students from “student table”
the following code can be used.
cursor.execute("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = cursor.fetchall()
print(*result, sep="\n")

..115..
– 15. DATA MANIPULATION THROUGH SQL
4. Read the following details. Based on that write a python script to display department
wise records.
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
Python script:
import sqlite3
connection=sqlite3.connect("organization.db")
cursor=connection.cursor()
cursor.execute("""create table employee(eno integer primary key, empname
varchar(20), esal integer, dept varchar(20));""")
cursor.execute("""insert into employee values ("1001", "Raja", "10500", "Sales");""")
cursor.execute("""insert into employee values ("1002", "Surya", "9000", "Purchase");""")
cursor.execute("""insert into employee values ("1003", "Peter", "8000",
"Production");""")
connection.commit()
print("Employee Details Department-wise :")
cursor.execute("""Select * from employee order by dept;""")
result=cursor.fetchall()
print(*result, sep="\n")
connection.close()
5. Read the following details. Based on that write a python script to display records in
descending order of Eno
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
Python script:
import sqlite3
connection=sqlite3.connect("organization.db")
cursor=connection.cursor()
cursor.execute("""create table employee(eno integer primary key, empname
varchar(20), esal integer, dept varchar(20));""")
cursor.execute("""insert into employee values ("1001", "Raja", "10500", "Sales");""")
cursor.execute("""insert into employee values ("1002", "Surya", "9000", "Purchase");""")
cursor.execute("""insert into employee values ("1003", "Peter", "8000",
"Production");""")
connection.commit()
print("Records in descending order of employee number:")
cursor.execute("""Select * from employee order by eno desc""")
result=cursor.fetchall()
print(*result,sep="\n")
connection.close()

..116..
– 15. DATA MANIPULATION THROUGH SQL
Part - IV
Answer the following questions: (5 Marks)
1. Write in brief about SQLite and the steps used to use it.
➢ SQLite is a simple relational database system, which saves its data in regular data files or
even in the internal memory of the computer.
➢ It is designed to be embedded in applications, instead of using a separate database server
program such as MySQL or Oracle.
➢ SQLite is fast, rigorously tested, and flexible, making it easier to work.
➢ Python has a native library for SQLite.
To use SQLite,
✓ Step 1 - import sqlite3
✓ Step 2 - create a connection using connect() method and pass the name of the
database file. If the database already exists the connection will open the same.
Otherwise, Python will open a new database file with the specified name.
✓ Step 3 - Set the cursor object cursor = connection.cursor(). It is a control structure
used to traverse and fetch the records of the database.
o Cursor has a major role in working with Python. All the commands will be
executed using cursor object only.
Example:
import sqlite3
connection=sqlite3.connect("organization.db")
cursor=connection.cursor( )
2. Write the Python script to display all the records of the following table using
fetchmany()
Icode Item_Name Rate
1003 Scanner 10500
1004 Speaker 3000
1005 Printer 8000
1008 Monitor 15000
1010 Mouse 700
Python script:
import sqlite3
connection=sqlite3.connect("inventory.db")
cursor=connection.cursor()
cursor.execute("""select * from product;""")
print("Displaying all records in the table")
result=cursor.fetchmany(5)
print(*result, sep="\n")
connection.close()

..117..
– 15. DATA MANIPULATION THROUGH SQL
3. What is the use of HAVING clause. Give an example python script.
➢ Having clause is used to filter data based on the group functions.
➢ This is similar to WHERE condition but can be used only with group functions.
➢ Group functions cannot be used in WHERE Clause but can be used in HAVING clause.
Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT GENDER,COUNT(GENDER) FROM Student
GROUP BY GENDER HAVING COUNT(GENDER)>3")
result = cursor.fetchall()
co = [i[0] for i in cursor.description]
print(co)
print(result)
OUTPUT:
['gender', 'COUNT(GENDER)']
[('M', 5)]
4. Write a Python script to create a table called ITEM with following specification.
Add one record to the table.
Name of the database :- ABC
Name of the table :- Item
Column name and specification :-
Icode : Integer and act as Primary Key
Item_Name : Character with length 25
Rate : Integer
Record to be added : 1008, Monitor, 15000
Python script:
import sqlite3
connection=sqlite3.connect("ABC.db")
cursor=connection.cursor()
cursor.execute("""drop table item;""")
cursor.execute("""create table item(icode integer primary key, itemname
varchar(25), rate integer);""")
cursor.execute("""insert into item values("1005","Printer","8000");""")
connection.commit()
connection.close()
print("Item table is created and a record is added Successfully")

..118..
– 15. DATA MANIPULATION THROUGH SQL
5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER
Suppno Name City Icode SuppQty
S001 Prasad Delhi 1008 100
S002 Anu Bangalore 1010 200
S003 Shahid Bangalore 1008 175
S004 Akila Hydrabad 1005 195
S005 Girish Hydrabad 1003 25
S006 Shylaja Chennai 1008 180
S007 Lavanya Mumbai 1005 325
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
ii) Increment the SuppQty of Akila by 40
Python script:
import sqlite3
connection=sqlite3.connect("item.db")
cursor=connection.cursor()
# i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
cursor.execute ("SELECT supplier.name, supplier.city, item.itemname FROM
supplier, item WHERE supplier.city <> ’Delhi’ ")
ans=cursor.fetchall ( )
for i in ans:
print()
# ii) Increment the SuppQty of Akila by 40
cursor.execute ("UPDATE supplier SET supplier.SuppQty =S uppQty + 40
WHERE name=’Akila’ ")
connection.commit()
connection.close()
ADDITIONAL QUESTIONS
1. Which method that returns the next number of rows (n) of the result set?
a) fetchall() b) fetchone() c) fetchmany() d) count()
2. In Sqlite3 Which symbol is used to print the list of all elements in a single line with space?
a) & b) * c) # d) ()
3. Which clause is used to filter data based on the group functions?
a) HAVING b) WHERE c) FILTER d) DISTINCT
4. Group functions cannot be used in ______ clause but can be used in HAVING clause.
a) HAVING b) WHERE c) COUNT d) SUM
5. Which of the following is not a function?
a) SUM() b) AVG() c) WHERE() d) COUNT()
6. Which of the following is an aggregate function?
a) TOTAL() b) AVERAGE() c) WHERE() d) COUNT()

..119..
– 15. DATA MANIPULATION THROUGH SQL
7. The sqlite3 module supports _____ kinds of placeholders
a) 1 b) 4 c) 3 d) 2
8. Sqlite3 have the following placeholders
a) ? and /name b) / and :name c) ? and :name d) / and ?name
9. In Python, the path of a file can be either represented as
a) “/” or “//” b) “/” or “\” c) “\\” or “:” d) “/” or “?”
10. What is the use of cursor object?
Cursor is a control structure used to traverse and fetch the records of the database. All the
SQL commands will be executed using cursor object only.
11. Write short note on fetchall(), fetchone() and fetchmany().
➢ cursor.fetchall() method is to fetch all rows from the database table
➢ cursor.fetchone()method returns the next row of a query result set or None in case there
is no row left.
➢ cursor.fetchmany() method returns the next number of rows (n) of the result set.
12. List out various clauses in SQL?
 DISTINCT  WHERE  GROUP BY
 ORDER BY  HAVING
13. Write short note on cursor.description().
➢ cursor.description contain the details of each column headings.
➢ It will be stored as a tuple and the first one that is 0(zero) index refers to the column
name.
➢ From index 1 onwards the values of the column(Records) are referred.
➢ Using this command, you can display the table’s Field names.
14. What is Sqlite_master?
The master table holds the key information about your database tables and it is called
sqlite_master.
15. How will you show the table list created in a database?
To show (display) the list of tables created in a database the following program can be
used.
Example:
import sqlite3
con = sqlite3.connect('Academy.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
Output:
[('Student',), ('Appointment',), ('Person',)]
16. What is the use of select query?
➢ “Select” is the most commonly used statement in SQL. The SELECT Statement in SQL is
used to retrieve or fetch data from a table in a database.

..120..
– 15. DATA MANIPULATION THROUGH SQL
➢ The syntax for using this statement is “Select * from table_name” and all the table data
can be fetched in an object in the form of list of lists.
Example:
import sqlite3
crsr = connection.cursor()
crsr.execute("SELECT * FROM Student")
ans= crsr.fetchall()
for i in ans:
print(i)

..121..
DATA VISUALIZATION USING PYTHON:
16
✓ LINE CHART, PIE CHART AND BAR CHART

Part - I
Choose the best answer: (1 Mark)
1. Which is a python package used for 2D charts?
(A) matplotlib.pyplot (B) matplotlib.pip
(C) matplotlib.numpy (D) matplotlib.plt
2. Identify the package manager for Python packages, or modules.
(A) Matplotlib (B) PIP
(C) plt.show() (D) python package
3. Which of the following feature is used to represent data and information graphically?
(A) Data List (B) Data Tuple
(C) Classes and Objects (D) Data Visualization
4. ______ is the collection of resources assembled to create a single unified visual display.
(A) Interface (B) Dashboard
(C) Objects (D) Graphics
5. Which of the following module should be imported to visualize data and information in
Python?
(A) csv (B) Pie chart (C) MySQL (D) matplotlib
6. _______ is a type of chart which displays information as a series of data points connected by
straight line segments.
(A) csv (B) Pie chart (C) Bar Chart (D)All the above
The correct answer is Line Chart or Line Graph
7. Read the code:
import matplotlib.pyplot as plt
plt.plot(3,2)
plt.show()
Identify the output for the above coding.

..122.. THAAI VIRUDHUNAGAR


– 16. DATA VISUALIZATION
8. Identify the right type of chart using the following hints.
Hint 1: This chart is often used to visualize a trend in data over intervals of time.
Hint 2: The line in this type of chart is often drawn chronologically.
(A) Line chart (B) Bar chart (C) Pie chart (D) Scatter plot
9. Read the statements given below. Identify the right option from the following for pie chart.
Statement A: To make a pie chart with Matplotlib, we can use the plt.pie() function.
Statement B: The autopct parameter allows us to display the percentage value using the
Python string formatting.
(A) Statement A is correct (B) Statement B is correct
(C) Both the statements are correct (D) Both the statements are wrong
Part - II
Answer the following questions: (2 Marks)
1. What is Data Visualization.
Data Visualization is the graphical representation of information and data. The objective
of Data Visualization is to communicate information visually to users.
2. List the general types of data visualization.
❖ Charts ❖ Tables ❖ Graphs
❖ Maps ❖ Infographics ❖ Dashboards
3. List the types of Visualizations in Matplotlib.
❖ Line plot ❖ Scatter plot ❖ Histogram
❖ Box plot ❖ Bar chart and ❖ Pie chart
4. How will you install Matplotlib?
✓ To install matplotlib, type the following in your command prompt:
python –m pip install –U matplotlib
5. Write the difference between the following functions: plt.plot([1,2,3,4]),
plt.plot([1,2,3,4], [1,4,9,16]).
Case 1: plt.plot([1,2,3,4])
matplotlib assumes it is a sequence of y values, and automatically generates the x values
for you. Python ranges start with 0, the default x vector has the same length as y but starts
with 0. Hence the x data are [0, 1, 2, 3].
Case 2: plt.plot([1,2,3,4], [1,4,9,16])
This plot takes many parameters, but the first two here are 'x' and 'y' coordinates. This
means, you have 4 co-ordinates according to these lists: (1,1), (2,4), (3,9) and (4,16).
Part - III
Answer the following questions: (3 Marks)
1. Draw the output for the following data visualization plot.
import matplotlib.pyplot as plt
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
plt.legend()
plt.xlabel('bar number')
..123..
– 16. DATA VISUALIZATION
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()
Output:

2. Write any three uses of data visualization.


❖ Data Visualization help users to analyze and interpret the data easily.
❖ It makes complex data understandable and usable.
❖ Various Charts in Data Visualization helps to show relationship in the data for one or more
variables.
3. Write the plot for the following pie chart output.
Code:
import matplotlib.pyplot as plt
sizes=[29.2,8.3,8.3,54.2]
labels=["Sleeping","Eating","Working","Playing"]
cols=['c','m’,’r’,'b’]
plt.pie(sizes, labels=labels, colors=cols,
autopct="%.2f")
plt.axes().set_aspect("equal")
plt.title("Interesting Graph \n Check it Out!!!!")
plt.show()

Part - IV
Answer the following questions: (5 Marks)
1. Explain in detail the types of pyplots using Matplotlib.
Line Chart:
➢ A Line Chart or Line Graph is a type of chart which displays information as a series of data
points called ‘markers’ connected by straight line segments.
➢ It is often used to visualize a trend in data over intervals of time – a time series – thus the
line is often drawn chronologically.

..124..
– 16. DATA VISUALIZATION
Example: Output:
import matplotlib.pyplot as plt
years = [2014, 2015, 2016, 2017, 2018]
total_populations = [8939007, 8954518,
8960387, 8956741, 8943721]
plt.plot (years, total_populations)
plt.title ("Year vs Population in India")
plt.xlabel ("Year")
plt.ylabel ("Total Population")
plt.show()
Bar Chart:
➢ It is one of the most common types of plot. It shows the relationship between a numerical
variable and a categorical variable.
➢ Bar chart represents categorical data with rectangular bars.
➢ The bars can be plotted vertically or horizontally.
➢ It’s useful when we want to compare a given numeric value on different categories.
➢ To make a bar chart with Matplotlib, we can use the plt.bar() function.
Example: Output:
import matplotlib.pyplot as plt
labels = ["TAMIL", "ENGLISH", "MATHS",
"PHYSICS", "CHEMISTRY", "CS"]
usage = [79.8, 67.3, 77.8, 68.4, 70.2, 88.5]
y_positions = range (len(labels))
plt.bar (y_positions, usage)
plt.xticks (y_positions, labels)
plt.ylabel ("RANGE")
plt.title ("MARKS")
plt.show()
Pie Chart:
➢ Pie Chart is probably one of the most common types of chart.
➢ It is a circular graphic which is divided into slices to illustrate numerical proportion.
➢ The point of a pie chart is to show the relationship of parts out of a whole.
➢ To make a Pie Chart with Matplotlib, we can use the plt.pie() function.
➢ The autopct parameter allows us to display the percentage value.
Example: Output:
import matplotlib.pyplot as plt
sizes = [89, 80, 90, 100, 75]
labels = ["Tamil", "English", "Maths", "Science", "Social"]
plt.pie (sizes, labels = labels, autopct = "%.2f ")
plt.axes().set_aspect ("equal")
plt.show()
..125..
– 16. DATA VISUALIZATION
2. Explain the various buttons in a matplotlib window.

➢ Home Button: The Home Button will help to return back to the original view.
➢ Forward/Back buttons: These buttons can be used to move back to the previous point
you were at, or forward again.
➢ Pan Axis: This cross-looking button allows you to click it, and then click and drag your
graph around.
➢ Zoom: The Zoom button lets you click on it, then click and drag a square that you would
like to zoom into specifically. Zooming in will require a left click and drag. You can
alternatively zoom out with a right click and drag.
➢ Configure Subplots: This button allows you to configure various spacing options with your
figure and plot.
➢ Save Figure: This button will allow you to save your figure in various forms.
3. Explain the purpose of the following functions:
a. plt.xlabel - It is used to assign label for X-axis.
b. plt.ylabel - It is used to assign label for Y-axis.
c. plt.title - It is used to assign title for the chart.
d. plt.legend() - It is used to add legend for the data plotted. It is needed
when more data are plotted in the chart.
e. plt.show() - It is used to display our plot.
ADDITIONAL QUESTIONS
1. The graphical representation of information and data is
a) Data Chart b) Data Visualization c) Data graph d) Data Monitor
2. The representation of information in a graphic format is
a) Dashboard b) Infographics c) Information graphics d) Box Plot
3. A collection of resources assembled to create a single unified visual display is
a) Dashboard b) Infographics
c) Information graphics d) Box Plot
4. A type of plot that shows the data as a collection of point is
a) Box plot b) Line plot c) Scatter plot d) pyplot
5. The method inside the file to display your plot is
a) plot.show() b) plt.show() c) plot.open() d) plt.open()
6. Which chart shows the relationship between a numerical variable and a categorical variable?
a) Bar chart b) Line chart c) Pie chart d) Histogram
7. Which of the following represents the frequency distribution of continuous variables?
a) Bar chart b) Line chart c) Pie chart d) Histogram
..126..
– 16. DATA VISUALIZATION
8. This cross-looking button allows you to click it, and then click and drag your graph around.
a) Home button b) Pan Axis
c) Configure Subplots button d) Zoom button
9. This button allows you to configure various spacing options with your figure and plot.
a) Home button b) Pan Axis
c) Configure Subplots button d) Zoom button
10. ______ and _______ are the two ways to display data in the form of a diagram.
a) Bar Graph b) Histogram c) a) and b) d) Dashboard
11. What is an Infographic?
An infographic (information graphic) is the representation of information in a graphic
format.
12. What is Dashboard?
➢ A dashboard is a collection of resources assembled to create a single unified visual display.
➢ Data visualizations and dashboards translate complex ideas and concepts into a simple
visual format.
➢ Patterns and relationships that are undetectable in text are detectable at a glance using
dashboard.
13. What is histogram?
Histogram refers to a graphical representation; that displays data by way of bars to show
the frequency of numerical data.
14. What is scatter plot?
A scatter plot is a type of plot that shows the data as a collection of points. The position
of a point depends on its two-dimensional value, where each value is a position on either the
horizontal or vertical dimension.
15. What is Box plot?
The box plot is a standardized way of displaying the distribution of data based on the five
number summary: minimum, first quartile, median, third quartile, and maximum.
16. What are the Key Differences Between Histogram and Bar Graph?
1. Histogram refers to a graphical representation; that displays data by way of bars to show
the frequency of numerical data. A bar graph is a pictorial representation of data that uses
bars to compare different categories of data.
2. A histogram represents the frequency distribution of continuous variables. Conversely, a
bar graph is a diagrammatic comparison of discrete variables.
3. Histogram presents numerical data whereas bar graph shows categorical data.
4. The histogram is drawn in such a way that there is no gap between the bars. On the other
hand, there is proper spacing between bars in a bar graph that indicates discontinuity.
5. 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.
6. In the case of a bar graph, it is quite common to rearrange the blocks, from highest to
lowest. But with histogram, this cannot be done, as they are shown in the sequence of
classes.
7. The width of rectangular blocks in a histogram may or may not be same while the width
of the bars in a bar graph is always same.

..127..
PUBLIC EXAMINATION QUESTIONS
(from March 2020 to March 2024)

PUBLIC ONE MARK QUESTIONS


March – 2020
1. The function which will give exact result when same arguments are passed are called
(a) Pure functions (b) Impure functions
(c) Partial functions (d) Dynamic functions
2. A sequence of immutable objects is called
(a) Derived data (b) Built in (c) List (d) Tuple
3. Which of the following members of a class can be handled only from within the class?
(a) Public members (b) Private members
(c) Protected members (d) Secured members
4. Two main measures for the efficiency of an algorithm are
(a) Data and space (b) Processor and memory
(c) Complexity and capacity (d) Time and space
5. Expand IDLE :
(a) Integrated Design Learning Environment
(b) Insert Development Learning Environment
(c) Integrated Develop Learning Environment
(d) Integrated Development Learning Environment
6. What is the output of the following snippet?
for i in range(2,10,2):
print(i,end="")
(a) 8 6 4 2 (b) 2 4 6 8 10 (c) 2 46 8 (d) 2 4 6
7. Evaluate the following function and write the output.
x=14.4
print(math.floor(x))
(a) 13 (b) 14 (c) 15 (d) 14.3
8. What will be the output of the following code?
str="NEW DELHI"
str[3]="-"
(a) NEW-DELHI (b) NE-DELHI (c) NEW DELHI (d) NEW-ELHI
9. The keys in Python dictionary is specified by
(a) ; (b)- (c) : (d) +
10. Class members are accessed through which operator?
(a) . (b) & (c) % (d) #

..128..
– PUBLIC QUESTIONS
11. What symbol is used for SELECT statement?
(a) Ω (b) σ (c) ∏ (d) x
12. The command to delete a table is :
(a) DROP (b) ALTER TABLE (c) DELETE (d) DELETE ALL
13. A CSV file is also known as a :
(a) Random File (b) String File (c) 3D File (d) Flat File
14. A framework for interfacing Python and C++ is :
(a) cytpes (b) Boost (c) SWIG (d) Cython
15. Which of the following is an organized collection of data?
(a) Records (b) Information (c) DBMS (d) Database
September - 2020
16. Which is the basic building block of computer programs?
(a) Argument (b) Parameter (c) Subroutine (d) Interface
17. Which functions build the abstract data type?
(a) Constructors (b) Data (c) List (d) Tuple
18. The process of binding a variable name with an object is called :
(a) Scope (b) Mapping (c) Namespaces (d) Memory
19. Which one of the following is not a factor to measure the execution time of an algorithm?
(a) Speed of the machine (b) Operating system
(c) Programming language used (d) Selection
20. Which key is pressed to execute Python Script?
(a) F5 (b) F2 (c) F1 (d) F3
21. Which statement is used to skip the remaining part of the loop and start with next iteration?
(a) break (b) pass (c) continue (d) null
22. Which of the following keyword is used to begin the function block?
(a) define (b) def (c) finally (d) for
23. In Python, which operator is used to display a string in multiple number of times?
(a) * (multiplication) (b) + (addition) (c) - (subtraction) (d) / (division)
24. Marks = [20, 40, 60, 80, 100]
print(Marks[-2])
What will be the output?
(a) 60 (b) 100 (c) 40 (d) 80
25. In Python, which of the following class declaration is correct?
(a) class class_name : (b) class class_name< >
(c) class class_name (d) class class_name[]
26. The Relational Database model was first proposed by :
(a) C.D. Darween (b) Chris Date
(c) E.F. Codd (d) Hugh Darween
27. Which is a Data Control Language command in SQL?
(a) Alter (b) Grant
(c) Truncate (d) Commit
..129..
– PUBLIC QUESTIONS
28. CSV is expanded as :
(a) Comma Separated Values (b) Condition Separated Values
(c) Comma Special Values (d) Condition Special Values
29. Which of the following is not a scripting language?
(a) Ruby (b) DBMS (c) Perl (d) JavaScript
30. Which SQL function returns the number of rows in a table?
(a) SUM() (b) MAX() (c) CHECK() (d) COUNT()
September - 2021
31. The small sections of code that are used to perform a particular task is called :
(a) Pseudo code (b) Subroutines (¢) Modules (d) Files
32. Let List = [2, 4, 6, 8, 10], then print(List[-2]) will result in :
(a) 4 (b) 10 (c) 6 (d) 8
33. SQLite falls under which database system?
(a) Hierarchical database system (b) Flat file database system
(c) Object oriented database system (d) Relational database system
34. The word comes from the name of a Persian Mathematician Abu Jafar Mohammed ibn-i Musa
al Khowarizmi is called :
(a) Algorithm (b) Flowchart (c) Syntax (d) Flow
35. Which one of the following character is used to give a single line comments in Python program?
(a) @ (b) # (c) & (d) &
36. What plays a vital role in Python programming?
(a) Structure (b) Statements (c) Indentation (d) Control
37. Which of the following keyword is used to exit a function block?
(a) finally (b) define (c) def (d) return
38. Strings in Python :
(a) Immutable (b) Changeable (c) Flexible (d) Mutable
39. Which of the following functions build the abstract data type?
(a) Recursive (b) Constructors (c) Nested (d) Destructors
40. The process of creating an object is called as
(a) Initialization (b) Constructor (c) Instantiation (d) Destructor
41. What is the acronym of DBMS?
(a) DataBase Management System (b) DataBase Management Symbol
(c) DataBasic Management System (d) DataBase Managing System
42. The clause used to sort data in a database :
(a) GROUP BY (b) SORT BY (c) SELECT (d) ORDER BY
43. The module which allows interface with the Windows Operating System is :
(a) csv module (b) OS module (c) getopt module (d) sys module
44. The process of binding a variable name with an object is called :
(a) Late binding (b) Scope (c) Early binding (d) Mapping
45. Using Matplotlib from within a Python Script, which method inside the file will display your plot?
(a) plot() (b) disp() (c) clear() (d) show()
..130..
– PUBLIC QUESTIONS
May - 2022
46. Which of the following is a distinct Syntactic black?
(a) Definition (b) Subroutines (c) Modules (d) Function
47. Which of the following will retrieve information from the data type?
(a) Recursive (b) Constructors (c) Nested (d) Selectors
48. Which of the following names of variables to object is called :
(a) Binding (b) Scope (c) Namespaces (d) Mapping
49. The word comes from the name of a Persian mathematician Abu Jafar Mohammed ibn-i Musa
al Khowarizmj is called :
(a) Algorithm (b) Flow chart (c) Syntax (d) Flow
50. Which Operator is also called as Comparative Operator »
(a) Logical Operator (b) Arithmetic Operator
(c) Assignment Operator (d) Relational Operator
51. ‘elif’ can be considered to be short form of ___________
(a) else if (b) nested if (c) if...elif (d) if..else
52. Which function is called as anonymous un-named function?
(a) Recursion (b) Lambda (c) Define (d) Built-in
53. What will be the output of the following code?
str1 =“Chennai Schools”
str1[7]=“-”
(a) Type Error (b) Chennai-Schools (c) Chennai (d) Chenna-School
54. If List=[17, 23, 41, 10] then, List.append(32) will result :
(a) [10, 17, 23, 32, 41] (b) [32, 17, 23, 41, 10]
(c) [41, 32, 23, 17, 10] (d) [17, 23, 41, 10, 32]
55. Which of the following method is used as destructor?
(a) __rem__() (b) __init__() (c) __del__() (d) __dest__ ()
56. A tuple is also known as :
(a) Attribute (b) Table (c) Field (d) Row
57. The clause used to sort data in a database.
(a) GROUP BY (b) SORT BY (c) SELECT (d) ORDER BY
58. The expansion of CRLF is :
(a) Control Router and Line Feed (b) Control Return and Line Feed
(c) Carriage Return and Line Feed (d) Carriage Return and Form Feed
59. A Framework for interfacing Python and C++ is :
(a) Cython (b) Ctypes (c) Boost (d) SWIG
60. SQLite falls under which database system 2
(a) Hierarchical Database System (b) Flat File Database System
(c) Object Oriented Database System (d) Relational Database System

..131..
– PUBLIC QUESTIONS
July - 2022
61. Which of the following is a unit of code that is often defined within a greater structure?
(a) Subroutines (b) Function (c) Files (d) Modules
62. Which of the following functions build the abstract data type?
(a) Constructors (b) Destructors (c) Recursive (d) Nested
63. Which scope refers to variables defined in current function?
(a) Local Scope (b) Global Scope (c) Module Scope (d) Function
Scope
64. Which of the following shortcut is used to create new Python Program?
(a) Ctrl + C (b) Ctrl + F (c) Cul+B (d) Ctrl + N
65. _______ is used to print more than one item on a single line.
(a) Semicolon (;) (b) Dollar ($) (c) Comma (,) (d) Colon (:)
66. Which is the most Comfortable loop?
(a) do..while (b) while (c) for (d) if..elif
67. Which of the following keyword is used to Dei the function block 2
(a) define (b) for (c) finally (d) def
68. What is Stride?
(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation:
69. What will be the result of the following Python code?
S =[ x ** 2 for x in range (5) ]
print (S)
(a) [0, 1, 2, 4, 5] (b) [0, 1, 4, 9, 16]
(c) [0, 1, 4, 9, 16, 25] (d) [1, 4, 9, 16, 25]
70. Class members are accessed through which operator?
(a) & (b) . (c) * (d) %
71. A table is known as ;
(a) Tuple (b) Attribute (c) Relation (d) Entity
72. The command to delete a table is :
(a) DROP (b) DELETE (c) DELETE ALL (d) ALTER TABLE
73. Which of the following mode is used when dealing with non-text files like image or exe files?
(a) Text made (b) Binary mode (c) xls mode (d) CSV mode
74. getopt () will return an empty array if there is no error in splitting strings to :
(a) argv variable (b) opt variable (c) args variable (d) ifile variable
75. The function that returns the largest value of the selected column is :
(a) MAX () (b) LARGE () (c) HIGH () (d) MAXIMUM()
March - 2023
76. _______ members are accessible from outside the class.
(a) Secured members (b) Public members.
(c) Private members (d) Protected members.

..132..
– PUBLIC QUESTIONS
77. Which of the following is not a keyword in Python?
(a) continue (b) break (c) operator (d) while
78. The small sections of code that are used to perform a particular task is called:
(a) Pseudo code (b) Subroutines (c) Modules (d) Files
79. The number of important control structures in Python :
(a) 5 (b) 3 (c) 6 (d) 4
80. Class members are accessed through operator.
(a) # (b) & (c) % (d) .
81. The database Model which represents the Parent-Child relationship:
(a) Hierarchical (b) Relational (c) Object (d) Network
82. The operator which is sed for concatenation?
(a) * (b) + (c) = (d) &
83. Importing C++ program in a Python program is called
(a) Interconnecting (b) Wrapping (c) Parsing (d) Downloading
84. command is used to remove a table from the database
(a) DELETE ALL (b) DROP TABLE (c) ALTER TABLE (d) DELETE
85. The function that returns the largest value of the selected column is:
(a) HIGH () (b) MAX() (c) MAXIMUM () (d) LARGE()
86. The datatype whose representation is known are called:
(a) Concrete datatype (b) Built-in datatype
(c) Abstract datatype (d) Derived datatype
87. A Function which calls itself, is called as :
(a) Lambda (b) Built-in (c) Return statement (d) Recursion
88. The mode which is used when dealing with non-text files like image or exe files :
(a) xls mode (b) Text mode (c) csv mode (d) Binary model
89. In dynamic programming, the technique of storing the previously calculated values is called :
(a) Memoization (b) Saving value property
(c) Mapping (d) Storing value property
90. Let set A={3, 6, 9}, set B={1, 3, 9}.
The result of the following snippet Print (set A set B)
(a) {1} (b) {3, 6, 9, 1, 3, 9} (c) {1, 3, 6, 9} (d) {3,9}
June - 2023
91. The variables in a function definition are called as:
(a) Subroutines (b) Function (c) Definition (d) Parameters
92. A sequence of immutable objects is called:
(a) Built in (b) List (c) Tuple (d) Derived
93. dataContainers for mapping names of variables to object is called
(a) Scope (b) Mapping (c) Binding (d) Namespaces
94. The two main factors which decide the efficiency of an algorithm are
(a) Processor and Memory (b) Complexity and capacity
(c) Time and Space (d) Data and space
..133..
– PUBLIC QUESTIONS
95. The Shortcut key used to create new Python program is:
(a) Ctrl + C (b) Ctrl + F (c) Ctrl + B (d) Ctrl + N
96. “elif” can be considered to be the abbreviation of:
(a) nested if (b) if..else (c) else if (d) if..elif
97. The function which is called anonymous un-named function:
(a) Lambda (b) Recursion (c) Function (d) Define
98. Is used as placeholders or replacement fields which get replaced along with format() function.
(a) {} (b) <> (c) ++ (d) ^^
99. Pick odd one in connection with collection data type.
(a) List (b) Tuple (c) Dictionary (d) Loop
100. The process of creating an object is called as:
(a) Constructor (b) Destructor (c) Initialize (d) Instantiation
101. A table is known as
(a) tuple (b) attribute (c) relation (d) entity
102. The clause used to sort data in a database:
(a) SORT BY (b) ORDER BY (c) GROUP BY (d) SELECT
103. The Command used to skip a row in a CSV file:
(a) next() (b) skip() (c) omit() (d) bounce()
104. The module which allows to interface with the Windows operating system:
(a) OS module (b) Sys module
(c) CSV module (d) getopt module
105. The most commonly used statement in SQL is:
(a) cursor (b) select (c) execute (d) commit

..134..
PUBLIC TWO MARK QUESTIONS
March - 2020
1. What is a Pair? Give an example.
2. What do you mean by Namespaces?
3. What is an Algorithm?
4. Write note on range() in loop.
5. Write categories of SQL commands.
6. Write the expansion of : (i) SWIG (ii) MinGW
7. What is the advantage of declaring a column as “INTEGER PRIMARY KEY”?
8. List the general types of data visualization.
9. What will be the output of the given Python program?
str="COMPUTER SCIENCE”
(a) print(str*2)
(b) print(str(0 : 7))
September - 2020
10. List the characteristics of interface.
11. What are the characteristics of modules?
12. What are tokens in Python? List the types.
13. What is the use of replace( ) in Python? Write the general format of replace( ).
14. Write the syntax to create list with suitable example in Python.
15. What are the advantages of DBMS?
16. What are the two ways to read a CSV file in Python?
17. List the types of visualizations in Matplotlib.
18. What are the advantages of user-defined functions?
September - 2021
19. Define Function with respect to programming language.
20. What are the different modes that can be used to test Python Program?
21. Write note on break statement.
22. Write the different types of function.
23. What is String 2
24. Write advantages of DBMS.
25. What is CSV File?
26. What is the theoretical difference between scripting language and other programming
language?
27. What is list in Python?
May - 2022
28. What is Abstract Data Type?
29. What is Mapping?
30. What is Searching? Write its types.
31. What are the different modes that can be used to test Python Program?
32. Write the syntax of creating a tuple with ‘n’ number of elements.

..135..
– PUBLIC QUESTIONS
33. Differentiate unique constraint and primary key constraint.
34. What is CSV file?
35. Define Data Visualization.
36. Write the syntax of getopt.getopt method.
July - 2022
37. Differentiate constructor and selector.
38. Write a short note on Namespaces.
39. Write note on range () in loop.
40. What is meant by scope of variables? Mention its types.
41. What is set in Python?
42. Mention few examples of Database Management System.
43. Differentiate compiler and interpreter.
44. Which method is used to fetch all rows from the database table?
45. What will be the output of the following code?
Strl = “School”
print (str1*3)
March - 2023
46. What is a Tuple? Give an example.
47. What is a scope?
48. How will you delete a string in Python?
49. Write note on range () in loop.
50. What is class?
51. What is Data Manipulation Language?
52. Mention the default modes of the File.
53. List the general types of data visualization.
54. What will be output of the following Python code?
Squares=[x**2 for x in range(1,11)]
print (squares)
June - 2023
55. Differentiate Interface and Implementation.
56. What is a pair?
57. Give an example.Write short notes on Tokens.
58. List the control structures in Python.
59. What are the main advantages of function?
60. What is data consistency?
61. Write the difference between table constraint and column constraint.
62. Write notes on: (i) MAX () function (ii) MIN () function
63. What is Set in Python?

..136..
PUBLIC THREE MARK QUESTIONS
March - 2020
1. Differentiate pure and impure function.
2. Write a note on Asymptotic notation.
3. Explain Ternary operator with example.
4. How recursive function works?
5. What will be the output of the following code?
list=[3**x for x in range(5)]
print(list)
6. Write short notes on TCL commands in SQL.
7. What is the difference between reader() and DictReader() function?
8. Mention the difference between fetchone() and fetchmany().
9. Write the output of the following program.
class Hosting:
def__init__(self, name):
self. _name=name
def display(self):
print(“ Welcome to”, self. name)
obj=Hosting(“Python Programming”)
obj.display()
September - 2020
10. (a) What is a selector?
(b) What are the parts of a program?
11. Write note on Dynamic Programming.
12. Write the syntax of Nested if..elif...else statement with example.
13. Write short note on public and private data members in Python.
14. Write note on types of DBMS users.
15. Write short note on DELETE, TRUNCATE, DROP command in SQL.
16. What are the applications of scripting languages?
17. Write short note on :
(a) GROUP BY (b) ORDER BY clause - in SQL
18. What will be the output of the given Python program?
a="“Computer”
b="Science”
x=a[:4]+b[len(b)-3:]
print(x)
September - 2021
19. Define Abstraction. What is abstract data type?
20. Define Local scope with an example.
21. What is an Algorithm? List any three characteristics of an algorithm.
22. What are the advantages of Tuples over a list 2

..137..
– PUBLIC QUESTIONS
23. What are class members 2 How do you define it?
24. Write any three DDL commands.
25. What is the difference between the write mode and append mode 2
26. Differentiate Python and C++.
27. Write short notes on Arithmetic operator with examples.
May - 2022
28. List the characteristics of an Algorithm.
29. List the difference between break and continue statements.
30. Write the rules of local variable.
31. What is sys.argv?
32. What is the use of ‘where clause’? Give a Python statement using the where clause.
33. Write any three uses of data visualization.
34. Write short notes on Arithmetic Operator with example.
35. Write a SQL statement using DISTINCT keyword.
36. Write a program to get the following output :
A
AB
ABC
ABCD
ABCDE
July - 2022
37. Write the syntax of ‘while’ loop.
38. Write the basic rules for global keyword in python.
39. Identify the module, operator, definition name for the following :
welcome.display()
40. Mention the difference between fetchone () and fetchmany ().
41. Write a python program to modify an existing file.
42. Write a SQL statement to modify the student table structure by adding a new field.
43. Write a note on open () function of Python. What are the differences between its two
methods?
44. List the general types of data visualization.
45. What is the output of the following program?
class Greeting :
def _ init _ (sell, name) :
self._ name = name
def display (self) :
print (“Good Morning”, self. name)
obj = Greeting (“Bindu Madhavan”)
obj.display ()

..138..
– PUBLIC QUESTIONS
March - 2023
46. Mention the characteristics of Interface.
47. What do you understand by Dynamic Programming?
48. Explain Ternary operator with an example.
49. Write the syntax of while loop.
50. Differentiate - ceil() and floor () function.
51. What is the difference between csvreader() method and DictReader () class?
52. Differentiate fetchone () and fetchmany ().
53. Write a Python program to display the given pattern.
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
54. Write about the steps of Python program executing C++ program using control statement.
June - 2023
55. Write any three characteristics of modules.
56. Write a note on Asymptotic notation.
57. What are string literals ?
58. Write a note on if..else Structure.
59. Write about composition in functions with an example.
60. What are the differences between List and Dictionary?
61. What is the role of DBA ?
62. Differentiate Python and C++.
63. Write a Python code to check whether a given year is leap year or not.

..139..
PUBLIC FIVE MARK QUESTIONS
March - 2020
1. (a) Discuss about Linear Search algorithm with example.
OR
(b) Explain input() and print() functions with example.
2. (a) (i) Write a program to display all 3 digit even numbers.
(ii) Write the output for the following program.
i=1
while(i<=6):
for j in range(1, i):
print(j,end="\t)
print(end="\n)
i+=1
OR
(b) Explain the following built-in functions :
(i) id() (ii) chr() (iii) round() (iv) type() (v) pow()
3. (a) Write the output for the following Python commands :
str1="Welcome to Python"
(i) print(str1) (ii) print(str1[11 : 17]) (iii) print(str1[11 : 17 : 2])
(iv) print(str1[: : 4]) (v) print(str1[: : —4])
OR
(b) How to define constructor and destructor in Python? Explain with example.
4. (a) Explain the different set operations supported by Python with suitable example.
OR
(b) Differentiate DBMS and RDBMS.
5. Write a SQL statement to create a table for employee having any five fields and Create a table
constraint for the employee table.
OR
(b) Write the features of Python over C++.
September - 2020
6. (a) Explain the types of variable scope.
OR
(b) Explain data types in Python with suitable example.
7. (a) Write the output for the following Python programs.
(i) j=15 (ii) k=5
while(j>=10): while(k<=9):
print(j, end="\t") for i in range(1, k):
j=i-1 print(i, end=’\t’)
else: k=k+1
print(“\n End of the loop”)

..140..
– PUBLIC QUESTIONS
OR
(b) Write about the following Python string functions.
(i) capitalize() (ii) swapcase() (iii) center() (iv) islower() (v) title()
8. (a) Debug the following Python program to get the given output :
Output:
Inside add( ) function x value is : 10
In main x value is : 10.
Program:
x=0
define add:
globally x:
x=x+10
print(“Inside add( ) function X value 15 :
add
print(“In main x value is 2)
OR
(b) What is set in Python? Explain the following set operations with suitable example.
(i) Union (ii) Intersection (iii) Difference
9. (a) Explain about constructors and destructors in Python with suitable example.
OR
(b) Explain the types of data model.
10. (a) Explain the types of constraints in SQL with suitable example.
OR
(b) List the differences between CSV and excel sheets (XLS) file.
September - 2021
11. (a) What is Binary Search? Discuss with example.
OR
(b) Discuss in detail about Tokens in Python.
12. (a) Write a detail note on for loop.
OR
(b) Explain the scope of variables with an example.
13. (a) (i) What is slicing?
(ii) What is output for the following Python Commands?
str = “Thinking with Python”
(i) print(str[::3]) (ii) print(str[::—3]) (iii) print(str[9:13])
OR
(b) What is the purpose of range()? Explain with an example.
14. (a) Explain the characteristics of DBMS.
OR
(b) Write the different types of constraints and their functions.

..141..
– PUBLIC QUESTIONS
15. (a) Write the Python script to display all the records of the following table using fetchmany().
Icode ItemName Rate
1003 Scanner 10500
1004 Speaker 3000
1005 Printer 8000
1008 Monitor 15000
1010 Mouse 700
OR
(b) Write any five key differences between Histogram and Bar Graph.
May - 2022
16. (a) (i) What are called Parameters?
(ii) Write a note on : Parameter without type and Parameter with type.
OR
(b) Explain LEGB rule with example.
17. (a) Explain Bubble Sort Algorithm with example.
OR
(b) Construct the following SQL statements in the student table,
(i) SELECT statement using GROUP BY Clause
(ii) SELECT statement using ORDER BY Clause
18. (a) Explain input() and output( ) functions with example.
OR
(b) Explain the purpose of the following functions :
(i) plt.xlabel (ii) plt.ylabel (iii) plt.title (iv) plt.legend( ) (v) plt.show()
19. (a) Write a detail note on for loop.
OR
(b) Differentiate Excel file and CSV file.
20. (a) Explain the different set operations supported by Python with suitable example.
OR
(b) Explain each word of the following command.
Python <filename.py> — <i> <C++ filename without cpp extension
July - 2022
21. (a) Discuss about linear search algorithm.
OR
(b) Explain the different types of function with an example.
22. (a) What is nested tuple? Explain with an example.
OR
(b) Explain about SQLite and the steps to be used.
23. (a) Write a detail note on ‘for’ loop.
OR
(b) Explain the different types of operators used in Python.

..142..
– PUBLIC QUESTIONS
24. (a) Write the different types of constraints and their functions?
OR
(b) Explain the characteristics of DBMS.
25. (a) Write the different methods to read a file in Python.
OR
(b) What is the purpose of range ()? Explain with an example.
March - 2023
26. (a) What is a List? Why List, can be called as pairs? Explain with suitable example.
OR
(b) Discuss about linear search algorithm.
27. (a) Discuss in details about Token in Python.
OR
(b) Explain the following built-in function.
(i) id() (ii) chr() (iii) round() (iv) type (v) pow()
28. (a) What is Nested Tuple? Explain with an example.
OR
(b) Explain the different types of relationship mapping.
29. (a) Write the syntax for getopt() and explain its arguments and return values.
OR
(b) Differentiate DBMS and RDBMS.
30. (a) Explain about differences between Histogram and Bar Graph.
OR
(b) Explain 'continue' statement with an example.
June - 2023
31. (a) What is Binary Search? Explain with an example.
OR
(b) How will you facilitate data abstraction? Explain it with suitable example.
32. (a) Explain input() and print() functions with examples.
OR
(b) Explain the scope of variables with an example.
33. (a) Explain about string operators in Python with suitable example.
OR
(b) What are the different ways to insert an element in a list? Explain with suitable example.
34. (a) Explain the characteristics of DBMS.
OR
(b) Explain about SQLite and the steps to be used.
35. (a) Write the different methods to read a file in Python.
OR
(b) Write any five features of Python.

..143..
MARCH - 2024

Register Number
PART-II
COMPUTER SCIENCE
(English Version)
Time Allowed : 3.00 Hours ] [ Maximum Marks : 70
Instructions : (1) Check the question paper for fairness of printing. If there is any
lack of fairness, inform the Hall Supervisor immediately.
(2) Use Blue or Black ink to write and underline and pencil to draw
diagrams.
PART - I
Note : i) Answer all the questions. 15 x 1 = 15
ii) Choose the most appropriate answer from the given four alternatives and write
the option code and the corresponding answer.
1. Which of the following is used to describe the worst case of an algorithm?
(a) Big W (b) Big A (c) Big O (d) Big S
2. The datatype whose representation is unknown are called as:
(a) Concrete datatype (b) Built-in datatype
(c) Abstract datatype (d) Derived datatype
3. Which key is pressed to execute Python Script?
(a) F1 (b) F5 (c) F3 (d) F2
4. Which of the following defines what an object can do?
(a) Interface (b) Operating System (c) Interpreter (d) Compiler
5. Which of the following security technique that regulates who can view or use resources in a computing
environment?
(a) Access control (b) Password (c) Certification (d) Authentication
6. Which of the following is the Slicing Operator?
(a) <> (b) {} (c) () (d) []
7. In Python the process of creating an object is called as _______
(a) Initialize (b) Constructor (c) Instantiation (d) Destructor
8. Pick the correct one to execute the given statement successfully.
if ____ : print(x, "is a leap year")
(a) x / 4 = 0 (b) x% * 2 = 0 (c) x% * 4 = 0 (d) x% * 4 ==0
9. What symbol is used for SELECT statement?
(a) X (b) σ (c) Ω (d) Π
10. If List [10, 20, 30, 40, 50] then List [2] = 35 will result:
(a) [10, 20, 35, 40, 50] (b) [35, 10, 20, 30, 40, 50]
(c) [10, 35, 30, 40, 50] (d) [10, 20, 30, 40, 50, 35]
..144..
– MARCH 2024
11. A CSV file is also known as a
(a) String File (b) Flat File (c) Random File (d) 3D File
12. The most commonly used statement in SQL is:
(a) execute (b) cursor (c) commit (d) select
13. What is the output of the following snippet in Python?
for x in range (5):
if x==2:
continue
print(x, end =’ ‘)
(a) 0 1 3 4 (b) 0 1 2 (c) 0 1 2 3 4 (d) 0 1 2 3
14. _________ is a collection of resources assembled to create a single unified visual display.
(a) Objects (b) Interface (c) Graphics (d) Dashboard
15. The clause used to sort data in a database:
(a) GROUP BY (b) SORT BY (c) SELECT (d) ORDER BY
PART II
Note : Answer any six questions. Question No. 24 is compulsory. 6 x 2 = 12
16. What is abstract data type?
17. What are the different operators that can be used in Python?
18. What is searching? Write its types.
19. Write the different types of function.
20. List the types of visualizations in Matplotlib.
21. What is the difference between Hierarchical and Network data model?
22. What is CSV file?
23. Which method is used to fetch all rows from the database table?
24. Write the use of pop() function in Python.
PART – III
Note : Answer any six questions. Question No. 33 is compulsory. 6 x 3 = 18
25. Differentiate pure and impure function.
26. What are the different ways to access the elements of a list? Give example.
27. Write a note on Asymptotic notation.
28. Using if..else..elif statement write a suitable program to display largest of 3 numbers.
29. Write a short note for the followings with suitable example.
(a) capitalize()
(b) swapcase()
30. How will you define Constructor and Destructor in Python?
31. What are the applications of scripting language?
32. What is the use of Where clause? Give a Python statement by using Where clause.
33. Write short notes on TCL Commands in SQL.

..145..
– MARCH 2024
PART – IV
Note : Answer all the following questions. 5 x 5 = 25
34. (a) How will you facilitate data abstraction? Explain it with suitable example.
OR
(b) What is Binary Search? Explain it with example.
35. (a) Explain input() and print() functions with examples.
OR
(b) Explain the scope of variables with an example.
36. (a) What is the purpose of range() function? Explain with an example.
OR
(b) Explain the following operators in Relational algebra with suitable examples.
(i) UNION (ii) INTERSECTION (iii) DIFFERENCE (iv) CARTESIAN PRODUCT
37. (a) What are the components of SQL? Write the commands for each.
OR
(b) Discuss the features of Python over C++.
38. (a) Write the different methods to read a file in Python.
OR
(b) Explain the various buttons in a matplotlib window.

-o0o-

..146..

You might also like