0% found this document useful (0 votes)
9 views107 pages

Xii CS Study Material

The document is a study material for XII STD Computer Science, covering various topics including functions, data abstraction, problem-solving techniques, and core Python concepts. It includes multiple-choice questions, short answer questions, and detailed explanations of programming concepts such as pure and impure functions, interfaces, and data types. The content is structured into units with chapters focusing on specific areas of computer science and programming.

Uploaded by

21aids25
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)
9 views107 pages

Xii CS Study Material

The document is a study material for XII STD Computer Science, covering various topics including functions, data abstraction, problem-solving techniques, and core Python concepts. It includes multiple-choice questions, short answer questions, and detailed explanations of programming concepts such as pure and impure functions, interfaces, and data types. The content is structured into units with chapters focusing on specific areas of computer science and programming.

Uploaded by

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

XII STD

COMPUTER SCIENCE
STUDY MATERIAL

1
TABLE OF CONTENTS
COMPUTER SCIENCE – II YEAR
UNIT NO CHAPTER TITLE

1 FUNCTION

UNIT – I
2 DATA ABSTRACTION
PROBLEM SOLVING
TECHNIQUES
3 SCOPING

4 ALGORITHMIC STRATEGIES

5 PYTHON-VARIABLES AND OPERATOR

6 CONTROL STRUCTURES
UNIT – II
CORE PYTHON
7 PYTHON FUNCTION

8 STRINGS AND STRING MANIPULATIONS

UNIT – III 9 LISTS, TUPLES, SETS AND DICTIONARY


MODULARITY AND
OOPS
10 PYTHON CLASSES AND OBJECTS

11 DATABASE CONCEPTS
UNIT – IV
DATABASE
CONCEPTS AND
12 STRUCTURED QUERY LANGUAGE(SQL)
MYSQL
13 PYTHON AND CSV FILES

14 IMPORTING C++ PROGRAM IN PYTHON


UNIT – V
INTEGRATING
15 DATA MANIPULATION THROUGH SQL
PYTHON WITH
MYSQL AND C++
DATA VISUALIZATION USING PYPLOT: LINE CHART,
16 PIE CHART AND BAR CHART

2
1. FUNCTIONS
Section – A
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 functions (B) Partial Functions
(C) Dynamic Functions (D) Pure functions
Section-B
Answer the following questions (2 Mark)
1. What is a subroutine?
 Subroutines are the basic building blocks of computer programs.
 Subroutines are small sections of code that are used to perform a particular task that can be used
repeatedly.
2. Define Function with respect to Programming language.
 A function is a unit of code that is often defined within a greater code structure.
 A function works on many kinds of inputs and produces a concrete output
3. Write the inference you get from X:=(78).
 X:=(78) is a function definition.
 Definitions bind values to names.
 Hence, the value 78 bound to the name ‘X’.
4. Differentiate interface and implementation.
Interface Implementation
 Interface just defines what an  Implementation carries out the
object can do, but won’t actually instructions defined in the interface
do it
5. Which of the following is a normal function definition and which is recursive function definition?
i) let sum x y:
return x + y Ans: Normal Function

3
ii) let disp :
print ‘welcome’ Ans: Normal Function

iii) let rec sum num:


if (num!=0) then return num + sum (num-1)
else
return num
Ans: Recursive Function
Section-C
Answer the following questions (3 Mark)
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 is controlled by sending functions to the object.
2. Why strlen is called pure function?
 strlen is a pure function because the function takes one variable as a parameter, and accesses it to find its
length.
 This function reads external memory but does not change it, and the value returned derives from the
external memory accessed.
3. What is the side effect of impure function. Give example.
 Impure Function has the following side effects,
 Function depends on variables or functions outside of its definition block.
 It never assure you that the function will behave the same every time it’s called.
 Example:
y: = 0
let inc (x:int) :int:=
y: = y + x
return (y)
 Here, the result of inc() will change when ‘y’ get changed.
 Hence, the side effect of inc () function is changing the data of the external variable ‘y’.
4. Differentiate pure and impure function.
Pure Function Impure Function
 Pure functions will give exact result when the  Impure functions never assure you that the
same arguments are passed. function will behave the same every time it’s
called.
 Pure function does not cause any side effects  Impure function causes side effects to its
to its output. output.
 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.
 They do not modify the arguments which are  They may modify the arguments which are
passed to them. passed.
 Example: strlen(), sqrt()  Example: random(), Date()

4
Section - D
Answer the following questions: (5 Mark)
1. What are called Parameters and write a note on
(i) Parameter without Type (ii) Parameter with Type
Answer:
 Parameters are the variables in a function definition
 Two types of parameter passing are,
1. Parameter Without Type
2. Parameter With Type
1. Parameter Without Type:
 Lets see an example of a function definition of Parameter Without Type:
(requires: b>=0 )
(returns: a to the power of b)
let rec pow a b:=
if b=0 then 1
else a * pow a (b-1)
 In the above function definition variable ‘ b’ is the parameter and the value passed to the variable ‘b’
is the argument.
 The precondition (requires) and postcondition (returns) of the function is given.
 We have not mentioned any types: (data types). This is called parameter without type.
 In the above function definition the expression has type ‘int’, so the function's return type also be ‘int’
by implicit.
2. Parameter With Type:
 Now let us write the same function definition with types,
(requires: b> 0 )
(returns: a to the power of b )
let rec pow (a: int) (b: int) : int :=
if b=0 then 1
else a * pow b (a-1)
 In this example we have explicitly annotating the types of argument and return type as ‘int’.
 Here, when we write the type annotations for ‘a’ and ‘b’ the parantheses are mandatory.
 This is the way passing parameter with type which helps the compiler to easily infer them.
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
 gcd
ii) Identify the statement which tells it is a recursive function
 let rec gcd a b :=
 “rec” keyword tells the compiler it is a recursive function
iii) Name of the argument variable
 ‘a’ and ‘b’

5
iv) Statement which invoke the function recursively
 gcd b (a mod b)
v) Statement which terminates the recursion
 return a
3. Explain with example Pure and impure functions.
Pure Function Impure Function
 Pure functions will give exact result when the  Impure functions never assure you that the
same arguments are passed. function will behave the same every time it’s
called.
 Pure function does not cause any side effects  Impure function causes side effects to its
to its output. output.
 The return value of the pure functions solely  The return value of the impure functions does
depends on its arguments passed. not solely depend on its arguments passed.
 They do not modify the arguments which are  They may modify the arguments which are
passed to them passed.
 If we call pure functions with same set of  If we call impure functions with same set of
arguments, we will always get the same return arguments, we might get the different return
values. values.
Example: sqrt()  Example: random()
let square x:= let random number:=
return: x * x a := random()
if a > 10 then
return: a
else
return: 10

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.
 The interface defines an object’s visibility to the outside world.
 For example when you press a light switch, the light goes on, you may not have cared how it splashed the
light
 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 is controlled by sending functions to the object.
 Implementation:
 Implementation carries out the instructions defined in the interface
 How the object is processed and executed is the implementation.
 A class declaration combines the external interface (its local state) with an implementation of that interface
(the code that carries out the behaviour).

6
 Example:
Let's take the example of increasing a car’s speed.
 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).
 In this case, the function call would be Speed (70): This is the interface.
 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.
2. DATA ABSTRACTION
Section – A
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
Section-B
Answer the following questions (2 Mark)
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 SELECTORS
 Constructors are functions that build the abstract  Selectors are functions that retrieve information
data type. from the data type.

7
 Constructors create an object, bundling together  Selectors extract individual pieces of
different pieces of information information from the object.

3. What is a Pair? Give an example.


 Any way of bundling two values together into one can be considered as a pair.
 Python provides a compound structure called Pair which is made up of list or Tuple.
 Example: lst:=[(0,10),(1,20)]
4. What is a List? Give an example.
 List can store multiple values of any type.
 List is constructed by placing expressions within square brackets separated by commas.
 Such an expression is called a list literal.
 Example: lst:=[10,20]
5. What is a Tuple? Give an example.
 A tuple is a comma-separated sequence of values surrounded with parentheses.
 Tuple is similar to a list but Cannot change the elements of a tuple.
 Example: Color= ('red', 'blue', 'Green')
Section-C
Answer the following questions (3 Mark)
1. Differentiate Concrete data type and abstract datatype.
CONCRETE DATA TYPE ABSTRACT DATA TYPE
 Concrete data types or structures (CDT's) are  Abstract Data Types (ADT's) offer a high level
direct implementations of a relatively simple view (and use) of a concept independent of its
concept. implementation.
 A concrete data type is a data type whose  Abstract data type the representation of a data
representation is known. type is unknown.
2. Which strategy is used for program designing? Define that Strategy.
 A powerful strategy for designing programs 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) -- Selector
(c) displaynum(n1) -- Selector
(d) eval(a/b) -- Selector
(e) x,y:= makeslope (m), makeslope(n) -- Constructor
(f) display() -- Selector
4. What are the different ways to access the elements of a list. Give example.
 The elements of a list can be accessed in two ways.
1. Multiple Assignment:
 Which unpacks a list into its elements and binds each element to a different name.
Example:
lst := [10, 20]

8
x, y := lst
 x will become10 and y will become 20.
2. Element Selection Operator:
 It is expressed using square brackets.
 Unlike a list literal, a square-brackets expression directly following another expression does not
evaluate to a list value, but instead selects an element from the value of the preceding expression.
Example:
lst[0]
10
lst[1]
20
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
Section - D
Answer the following questions: (5 Mark)
1. How will you facilitate data abstraction. Explain it with suitable example.
 Data abstraction is supported by defining an abstract data type (ADT), which is a collection of
constructors and selectors.
 To facilitate data abstraction, you will need to create two types of functions:
 Constructors
 Selectors
a) Constructor:
 Constructors are functions that build the abstract data type.
 Constructors create an object, bundling together different pieces of information.
 For example, say you have an abstract data type called city.
 This city object will hold the city’s name, and its latitude and longitude.
 To create a city object, you’d use a function like city = makecity (name, lat, lon).
 Here makecity (name, lat, lon) is the constructor which creates the object city.
b) Selectors:
 Selectors are functions that retrieve information from the data type.
 Selectors extract individual pieces of information from the object.
 To extract the information of a city object, you would use functions like
 getname(city)
 getlat(city)
 getlon(city)
These are the selectors because these functions extract the information of the city object.
2. What is a List? Why List can be called as Pairs. Explain with suitable example.
LIST:
 List is constructed by placing expressions within square brackets separated by commas.
9
 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.
 The elements of a list can be accessed in two ways.
1. Multiple Assignment:
 Which unpacks a list into its elements and binds each element to a different name.
Example:
lst := [10, 20]
x, y := lst
 x will become10 and y will become 20.
2. Element Selection Operator:
 It is expressed using square brackets.
 Unlike a list literal, a square-brackets expression directly following another expression does not
evaluate to a list value, but instead selects an element from the value of the preceding expression.
Example:
lst[0]
10
lst[1]
20
PAIRS:
 Any way of bundling two values together into one can be considered as a pair.
 Python provides a compound structure called Pair which is made up of list or Tuple.
Example: lst:=[(0,10),(1,20)]

3. How will you access the multi-item. Explain with example.


MULTI-ITEM:
 The structure construct in OOP languages it's called class construct is used to represent multi-part
objects where each part is named.
 Consider the following pseudo code:
class Person:  Class Name
creation( )  Function
firstName := " "  firstName := “Padmashri”
lastName := " "  lastName := “Baskar” Variables
id := " "  id := "9942221234”
email := " "  email := [email protected]
p1:= Person()  Creation of an Object
 The class (structure) construct defines the form for multi-part objects that represent a person.
 Person is referred to as a class or a type, while p1 is referred to as an object or an instance.
 Using class you can create many objects of that type.
 Class defines a data abstraction by grouping related data items.

10
 A class as bundled data and the functions that work on that data that is using class we can access multi-
part items.
3. SCOPING
Section – A
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 member (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 sub-classes is called
(A) Public members (B)Protected members (C) Secured members (D) Private members
Section-B
Answer the following questions (2 Mark)
1. What is a scope?
 Scope refers to the visibility of variables, parameters and functions 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 scope should be used for variables because; it limits a variable's scope to a single definition.
 That is the variables are visible only to that part of the code.
 Example:
Disp( ):
a := 7  Local Scope
print a
Disp( )
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 (name : = object).
 Example: a:=5
11
 Here the variable ‘a’ is mapped to the value ‘5’.
5. How Python represents the private and protected Access specifiers?
 Python prescribes a convention of adding a prefix (double underscore) results in a variable name or
method becoming private.
 Example: self. n2=n2
 Adding a prefix _ (single underscore) to a variable name or method makes it protected.
 Example: self._sal = sal
Section-C
Answer the following questions (3 Mark)
1. Define Local scope with an example.
 Local scope refers to variables defined in current function.
 A function will always look up for a variable name in its local scope.
 Only if it does not find it there, the outer scopes are checked.
 Example:
Disp( ):
a := 7  Local Scope
print a
Disp( )
 OUTPUT: 7
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.
 Global variable can be accessed inside or outside of all the functions in a program.
 Example:
a:=10  Global Scope
Disp( )
a := 7  Local Scope
print a
Disp( )
print a
 OUTPUT:
7
10
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.
 When a compiler or interpreter searches for a variable in a program, it first search Local, and then search
Enclosing scopes.
 EXAMPLE:
Disp( ):
a:=10
Disp1( ):
print a
Disp1( )
12
print a
Disp( ):
 OUTPUT:
10
10
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.
 Access control is a selective restriction of access to data.
 In OOPS Access control is implemented through access modifiers.
5. Identify the scope of the variables in the following pseudo code and write its output.
color:= Red
mycolor():
b:=Blue
myfavcolor():
g:=Green
print color, b, g
myfavcolor()
print color, b
mycolor()
print color
OUTPUT:
Red Blue Green
Red Blue
Red
Scope of Variables:
Variables Scope
color Global
b Enclosed
g Local
Section - D
Answer the following questions: (5 Mark)
1. Explain the types of scopes for variable or LEGB rule with example.
SCOPE:
 Scope refers to the visibility of variables, parameters and functions in one part of a program to another part
of the same program.
LEGB RULE:
 The LEGB rule is used to decide the order in which the scopes are to be searched for scope resolution.
 The scopes are listed below in terms of hierarchy (highest to lowest).

13
i) LOCAL SCOPE:
 Local scope refers to variables defined in current function.
 A function will always look up for a variable name in its local scope.
 Only if it does not find it there, the outer scopes are checked.
 Example:
Disp( ):
a := 7  Local Scope
print a
Disp( )
 OUTPUT: 7
ii) 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.
 When a compiler or interpreter searches for a variable in a program, it first search Local, and then search
Enclosing scopes.
 EXAMPLE:
Disp( ):
a:=10
Disp1( ):
print a
Disp1( )
print a
Disp( ):
 OUTPUT:
10
10
iii) GLOBAL SCOPE:
 A variable which is declared outside of all the functions in a program is known as global variable.
 Global variable can be accessed inside or outside of all the functions in a program.
 Example:
a:=10  Global Scope
Disp( )
a := 7  Local Scope
print a

14
Disp( )
print a
 OUTPUT:
7
10
iv) 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
2. Write any Five Characteristics of Modules.
The following are the desirable characteristics of a module.
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.
 A single procedure can be developed for reuse, eliminating the need to retype the code many times.
 Programs can be designed easily because a small team deals with only a small part of the entire code.
 Modular programming allows many programmers to collaborate on the same application.
 The code is stored across multiple files.
 Code is short, simple and easy to understand.
 Errors can easily be identified, as they are localized to a subroutine or function.
 The same code can be used in many applications.
 The scoping of variables can easily be controlled.
4. ALGORITHMIC STRATEGIES
Section – A
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) Insertion sort (C) Selection sort (D) All the above
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 in called as
(A) Algorithmic Solution (B) Algorithmic outcomes
(C) Algorithmic problems (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

15
(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
Section-B
Answer the following questions (2 Mark)
1. What is an Algorithm?
 An algorithm is a finite set of instructions to accomplish a particular task.
 It is a step-by-step procedure for solving a given problem.
2. Write the phases of performance evaluation of an algorithm.
 The performance evaluation of an algorithms can be divided into two different phases
 A Priori estimates:
This is a theoretical performance analysis of an algorithm.
 A Posteriori testing:
This is called performance measurement.
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 sublist in the lower positions of the list.
4. What is Sorting?
 Sorting is a process of arranging group of items in an ascending or descending order
 Bubble Sort, Quick Sort, Heap Sort, Merge Sort, Selection Sort are the various sorting algorithms.
5. What is searching? Write its types.
 A Search algorithm is the step-by-step procedure used to locate a particular value from a list.
 Example: Linear Search, Binary Search
Section-C
Answer the following questions (3 Mark)
1. List the characteristics of an algorithm.
 Input
 Output
 Finiteness
 Definiteness
 Effectiveness
 Correctness
 Simplicity
 Unambiguous
 Feasibility
16
 Portable
 Independent
2. Discuss about Algorithmic complexity and its types.
ALGORITHMIC COMPLEXITY:
 The complexity of an algorithm f(n) gives the running time and/or the storage space required by the
algorithm in terms of n as the size of input data.
TYPES OF COMPLEXITY:
1. Time Complexity
 The Time complexity of an algorithm is given by the number of steps taken by the algorithm to
complete the process.
2. 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 use meaningful statements about time and space complexity.
 The following three asymptotic notations are mostly used to represent time complexity of algorithms:
(i) Big O
 Big O is often used to describe the worst-case of an algorithm.
(ii) Big Ω
 Big Ω is used to describe the lower bound (best-case).
(iii) Big Θ
 Time complexity is n log n in both best-case and worst-case.
5. What do you understand by Dynamic programming?
 Dynamic programming is used when the solution to a problem can be viewed as the result of a sequence of
decisions.
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 uses Memoization.
Section - D
Answer the following questions: (5 Mark)
1. Explain the characteristics of an algorithm.
Characteristics Meaning
Input Zero or more quantities to be supplied.
Output At least one quantity is produced.
17
Finiteness Algorithms must terminate after finite number of steps.

Definiteness All operations should be well defined.


Effectiveness Every instruction must be carried out effectively.
Correctness The algorithms should be error free.
Simplicity Easy to implement.
Algorithm should be clear and unambiguous. Each of its steps should be clear and
Unambiguous
must lead to only one meaning.
Feasibility Should be feasible with the available resources.

Portable An algorithm should be generic, independent and able to handle all range of inputs.

An algorithm should have step-by-step directions, which should be independent of


Independent
any programming code.
2. Discuss about Linear search algorithm.
LINEAR SEARCH:
 Linear search also called sequential search is a sequential method for finding a particular value in a list.
 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. If no match is found, display the
search element not found.
3. If no match is found, display the search element not found.
Example:
 To search the number 25 in the array given below, linear search will go step by step in a sequential
order starting from the first element in the given array.
 if the search element is found that index is returned otherwise the search is continued till the last index
of the array.
 In this example number 25 is found at index number 3.
index 0 1 2 3 4
values 10 12 20 25 30

Snippet:
Input: values[ ]={10,12,20,25,30}
Target=25
Output:
3

18
3. What is Binary search? Discuss with example.
BINARY SEARCH:
 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:
a) If the search element is equal to the middle element of the array, then return the index of the
middle element.
b) If not, then compare the middle element with the search value,
c) If (Search element > number in the middle index), then select the elements to the right side
of the middle index, and go to Step-1.
d) If (Search element < 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.
Binary Search Working principles with example:
 List of elements in an array must be sorted first for Binary search.
 The array is being sorted in the given example and it is suitable to do the binary search algorithm.
 Let us assume that the search element is 60 and we need to search the location or index of search
element 60 using binary search.

 First, we find index of middle element of the array by using this formula :
mid = low + (high - low) / 2
 Here it is, 0 + (9 - 0 ) / 2 = 4. So, 4 is the mid value of the array.

 Compare the value stored at index 4 with target value, which is not match with search element. As the
search value 60 > 50.

 Now we change our search range low to mid + 1 and find the new mid value as index 7.
 We compare the value stored at index 7 with our target value.

 Element not found because the value in index 7 is greater than search value . ( 80 > 60)
 So, the search element must be in the lower part from the current mid value location

19
 Now we change our search range low to mid - 1 and find the new mid value as index 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.
4. Explain the Bubble sort algorithm with example.
 Bubble sort is a simple sorting algorithm, it 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, which shows the values in an
array is sorted.
 It is named so because, the smaller elements "bubble" to the top of the list.
 It is too slow and less efficient when compared to other sorting methods.
Pseudo code
1. Start with the first element i.e., index = 0, compare the current element with the next element of the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next or right side of the element, move to the next element.
4. Go to Step 1 and repeat until end of the index is reached.
Example:
 Consider an array with values {15, 11, 16, 12, 14, 13}
 Below, we have a pictorial representation of how bubble sort.

 The above pictorial example is for iteration-1.


 Similarly, remaining iteration can be done.
 The final iteration will give the sorted array.
 At the end of all the iterations we will get the sorted values in an array as given below:

20
5. Explain the concept of Dynamic programming with suitable example.
 Dynamic programming is 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 (i.e) the problem can be divided into
smaller sub-problems.
 Results of the sub-problems can be re-used to complete the process.
 Dynamic programming approaches are used to find the solution in optimized way.
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 uses Memoization.
Fibonacci Iterative Algorithm with Dynamic Programming Approach
 The following example shows a simple Dynamic programming approach for the generation of
Fibonacci series.
 Initialize f0=0, f1 =1
 step-1: Print the initial values of Fibonacci f0 and f1
 step-2: Calculate fibanocci fib ← f0 + f1
 step-3: Assign f0← f1, f1← fib
 step-4: Print the next consecutive value of fibanocci fib
 step-5: Goto step-2 and repeat until the specified number of terms generated
 For example if we generate fibonacci series upto 10 digits, the algorithm will generate the series as
shown below:
 The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55
5. PYTHON - VARIABLES AND OPERATORS
Section – A
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

21
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational C) Logical D) Assignment
Section-B
Answer the following questions (2 Mark)
1. What are the different modes that can be used to test Python Program ?
 Two modes of Python programming are,
 Interactive mode allows us to write codes in Python command prompt ( >>> ).
 Script mode is used to create and edit python source file with the extension .py
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
5) Literals
3. What are the different operators that can be used in Python ?
 Operators are special symbols which represent computations, conditional matching in programming.
 Operators are categorized as Arithmetic, Relational, Logical, Assignment and Conditional.
4. What is a literal? Explain the types of literals ?
 Literal is a raw data given in a variable or constant.
 In Python, there are various types of literals. They are,
1) Numeric Literals consists of digits
2) String literal is a sequence of characters surrounded by quotes.
3) Boolean literal can have any of the two values: True or False.
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
Section-C
Answer the following questions (3 Mark)
1. Write short notes on Arithmetic operator with examples.
 An arithmetic operator is a mathematical operator used for simple arithmetic.
 It takes two operands and performs a calculation on them.
 Arithmetic Operators used in python:

22
2. What are the assignment operators that can be used in Python?
 ‘=’ is a simple assignment operator to assign values to variable.
 There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //=.
 Example:
a=5 # assigns the value 5 to a
a+=2 # a=a+2, add 2 to the value of ‘a’ and stores the result in ‘a’.
3. Explain Ternary operator with examples.
 Ternary operator is also known as conditional operator that evaluates 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 # Output: min = 50
4. Write short notes on Escape sequences with examples.
 In Python strings, the backslash "\" is a special character, also called the "escape" character.
 It is used in representing certain whitespace characters.
 Python supports the following escape sequence characters.

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 = "This is Python"
C = "C"
multiline_str = "' This is a multiline string with more than one line code."'
Section - D
Answer the following questions: (5 Mark)
1. Describe in detail the procedure Script mode programming.
SCRIPT MODE PROGRAMMING:
 A script is a text file containing the Python statements.

23
 Once the Python Scripts is created, they are reusable , it can be executed again and again without retyping.
 The Scripts are editable.
(i) Creating Scripts in Python
1. Choose File → New File or press Ctrl + N in Python shell window.
2. An untitled blank script text editor will be displayed on screen.
3. Type the code in Script editor as given below,
(ii) Saving Python Script
(1) Choose File → Save or Press Ctrl + S
(2) Now, Save As dialog box appears on the screen.
(3) In the Save As dialog box
 Select the location to save your Python code.
 Type the file name in File Name box.
 Python files are by default saved with extension .py.
 So, while creating scripts using Python Script editor, no need to specify the file extension.
(4) Finally, click Save button to save your Python script.
(iii) 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.
 To correct the errors, go back to Script editor, make corrections, save the file and execute it again.
(3) For all error free code, the output will appear in the IDLE window of Python.
2. Explain input() and print() functions with examples.
Input and Output Functions
 A program needs to interact with the user to accomplish the desired task; this can be achieved using
Input-Output functions.
 The input() function helps to enter data at run time by the user
 The output function print() is used to display the result of the program on the screen after execution.
1) input() function
 In Python, input( ) function is used to accept data as input at run time.
 The syntax for input() function is,

 “Prompt string” in the syntax is a message to the user, to know what input can be given.
 If a prompt string is used, it is displayed on the monitor; the user can provide expected data from the
input device.
 The input( ) takes typed data from the keyboard and stores in the given variable.
 If prompt string is not given in input( ), the user will not know what is to be typed as input.
 Example 1:
>>> city=input (“Enter Your City: ”)
Enter Your City: Madurai
 The input() using prompt string takes proper input and produce relevant output.
Input() using Numerical values:
 The input ( ) accepts all data as string or characters but not as numbers.

24
 The int( ) function is used to convert string data as integer data explicitly.
 Example:
x = int (input(“Enter Number 1: ”))
y = int (input(“Enter Number 2: ”))
print (“The sum = ”, x+y)
Output:
Enter Number 1: 34
Enter Number 2: 56
The sum = 90
2) Print() function
 In Python, the print( ) function is used to display result on the screen.
 Syntax for print( ):
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3” ……)
 Example:
>>> print (“Welcome to Python Programming”)
Welcome to Python Programming
>>> x = 5
>>> y = 6
>>> z = x + y
>>> print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
Output:
The sum of 5 and 6 is 11
 The print ( ) evaluates the expression before printing it on the monitor.
 The print () displays an entire statement which is specified within print ( ).
 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, identifiers or keywords.
1) Identifiers

25
 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, total_marks, regno, num1
2) Keywords
 Keywords are special words used by Python interpreter to recognize the structure of program.
 Keywords have specific meaning for interpreter, they cannot be used for any other purpose.
 Python Keywords: false, class, If, elif, else, pass, break etc.
3) Operators
 Operators are special symbols which represent computations, conditional matching in programming.
 Operators are categorized as Arithmetic, Relational, Logical, Assignment and Conditional.
 Value and variables when used with operator are known as operands.
 Example:
a=100
b=10
print ("The Sum = ",a+b)
print ("The a > b = ",a>b)
print ("The a > b or a == b = ",a>b or a==b)
a+=10
print(“The a+=10 is =”, a)
Output:
The Sum = 110
The a>b = True
The a > b or a == b = True
The a+=10 is= 110

4) Delimiters
 Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries and
strings.
 Following are the delimiters: ( ), [ ], { }, ;, +=, ...

5) Literals
 Literal is a raw data given in a variable or constant.
 In Python, there are various types of literals. They are,
1) Numeric Literals consists of digits and are immutable
2) String literal is a sequence of characters surrounded by quotes.
3) Boolean literal can have any of the two values: True or False.
6. CONTROL STRUCTURES
Section – A
Choose the best answer (1 Mark)
1. How many important control structures are there in Python?
A) 3 B) 4 C) 5 D) 6
26
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) 1 2 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) no output
9. Which amongst this is not a jump statement ?
A) for B) goto 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) !
Section-B
Answer the following questions (2 Mark)
1. List the control structures in Python.
Three important control structures are,
 Sequential
 Alternative or Branching
 Iterative or Looping
2. Write note on break statement.
break statement :
 The break statement terminates the loop containing it.
 Control of the program flows to the statement immediately after the body of the loop.
3. Write is the syntax of if..else statement
Syntax:
if <condition>:

27
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
 The range() is a built-in function.
 To generate series of values between two numeric intervals.
 The syntax of range() is as follows:
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.
Section-C
Answer the following questions (3 Mark)
1. Write a program to display
A
AB
ABC
ABCD
ABCDE
CODE:
for i in range(65, 70):
for j in range(65, i+1):
print(chr(j), end= '')
print(end='\n')
2. Write note on if..else structure.
 The if .. else statement provides control to check the true block as well as the false block.
 if..else statement thus provides two possibilities and the condition determines which BLOCK is to be
executed.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
3. Using if..else..elif statement write a suitable program to display largest of 3 numbers.
CODE:
x= int(input("Enter the first number:"))
y= int(input("Enter the second number:"))
z= int(input("Enter the third number:"))

28
if(x>=y)and(x>=z):
biggest=x
elif(y>=z):
biggest=y
else:
biggest=z
print("The biggest number is",biggest)
OUTPUT
Enter the first number:3
Enter the second number:6
Enter the third number:4
The biggest number is 6
4. Write the syntax of while loop.
Syntax:
while <condition>:
statements block 1
[else:
statements block2]
5. List the differences between break and continue statements.
break continue
The break statement terminates the loop The Continue statement is used to skip the
containing it. remaining part of a loop and
Control of the program flows to the statement Control of the program flows start with next
immediately after the body of the loop. iteration.
Syntax: Syntax:
break continue
Section - D
Answer the following questions: (5 Mark)
1. Write a detail note on for loop.
 The for loop is usually known as definite loop, because the programmer known exactly how many times
the loop will be executed.
Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
 The for …. in statement is a looping statement used in python to iterate over a sequence of objects.
 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 variables accesses each item of the sequence on each iteration until it reaches last item in the
sequence.
 The range() is a built-in function.

29
 To generate series of values between two numeric intervals.
The syntax of range() is as follows:
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:
for i in range(2,10,2):
print (i,end=' ')
Output:
2468
2. Write a detail note on if..else..elif statement with suitable example.
Nested if..elif...else statement:
 When we need to construct a chain of if statement(s) then ‘elif’ clause can be used instead of ‘else’.
 ‘elif’ clause combines if..else-if..else statements to one if..elif…else.
 ‘elif’ can be considered to be abbreviation of ‘else if’.
 In an ‘if’ statement there is no limit of ‘elif’ clause that can be used, but an ‘else’ clause if used should be
placed at the end.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
 In the syntax of if..elif..else mentioned above, 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:
x= int(input("Enter the first number:"))
y= int(input("Enter the second number:"))
z= int(input("Enter the third number:"))
if(x>=y)and(x>=z):
biggest=x
elif(y>=z):
biggest=y
else:
biggest=z
print("The biggest number is",biggest)

30
Output :
Enter the first number:3
Enter the second number:6
Enter the third number:4
The biggest number is 6
3. Write a program to display all 3 digit odd numbers.
CODE:
for x in range(101, 1000, 2):
print(x, end='\t')
4. Write a program to display multiplication table for a given number.
CODE:
num=int(input("Display Multiplication Table of "))
for i in range(1,11):
print(i, 'x' ,num, '=' , num*i)
Output:
Display Multiplication Table of 2
1x2=2
2x2=4
3x2=6
4x2=8
5 x 2 = 10
6 x 2 = 12
7 x 2 = 14
8 x 2 = 16
9 x 2 = 18
10 x 2 = 20
=== Code Execution Successful ===

7. PYTHON FUNCTIONS
Section – A
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.

31
(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
Section-B
Answer the following questions (2 Mark)
1. What is function?
 Functions are named blocks of code that are designed to do one specific job.
 Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
2. Write the different types of function.
TYPES OF FUNCTION:
1. User-defined functions
2. Built-in functions
3. Lambda functions
4. 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, i.e., area where you can refer
(use) it.
 Scope holds the current set of variables and their values.
 The two types of scopes are- local scope and 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/block.
6. What is base condition in recursive function
 A recursive function calls itself.
 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 based on the limit given by default.
 So, It also allows you to change the limit using sys.setrecursionlimit (limit_value).
 Example:
import sys
sys.setrecursionlimit(3000)
def fact(n):
if n == 0:

32
return 1
else:
return n * fact(n-1)
print(fact (2000))
Section-C
Answer the following questions (3 Mark)
1. Write the rules of local variable.
• A variable with local scope can be accessed only within the function/block that it is created in.
• When a variable is created inside the function/block, the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal arguments are also local to function.
2. Write the basic rules for global keyword in python.
The basic rules for global keyword in Python are:
• 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 read and write a 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.
Example:
x=0
def add():
global x
x=x+5
add()
print ("Global X :", x)

Output:
Global X : 5
4. Differentiate ceil() and floor() function?
ceil() floor()
 Returns the smallest integer greater than or  Returns the largest integer less than or equal
equal to x to x
Example: Example:
import math import math
print(math.ceil (5.5)) print(math.floor (5.5))
Output: Output:
6 5
5. Write a Python code to check whether a given year is leap year or not.
CODE:
n=int(input("Enter the year"))

33
if(n%4==0):
print ("Leap Year")
else:
print ("Not a Leap Year")
Output:
Enter the year 2012
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.
• For example, if we wish to take a numeric value as a input from the user, we take the input string from the
user using the function input() and apply eval() function to evaluate its value.
• >>> n1 = eval (input ("Enter a number: "))
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?
When defining functions there are multiple things that need to be noted;
• Function blocks begin with the keyword “def” followed by function name and parenthesis ().
• Any input parameters should be placed within these parentheses.
• The code block always comes after a colon (:) and is indented.
• The statement “return [expression]” exits a function, and it is optional.
• A “return” with no arguments is the same as return None.
Section - D
Answer the following questions: (5 Mark)
1. Explain the different types of function with an example.
 Functions are named blocks of code that are designed to do one specific job.
 Types of Functions
 User defined Function
 Built-in Function
 Lambda Function
 Recursion Function
i) BUILT-IN FUNCTION:
• Built-in functions are Functions that are inbuilt with in Python.
• print(), echo() are some built-in function.
ii) USER DEFINED FUNCTION:
• Functions defined by the users themselves are called user defined function.
 Functions must be defined, to create and use certain functionality.
 Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
 Syntax:
def <function_name ([parameter1, parameter2…] )> :
<Block of Statements>
return <expression / None>
34
 EXAMPLE:
def area(w,h):
return w * h
print (area (3,5))
iii) LAMBDA FUNCTION:
• 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.
USE OF LAMBDA OR ANONYMOUS FUNCTION:
• Lambda function is mostly used for creating small and one-time anonymous function.
EXAMPLE:
sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10

iv) RECURSIVE FUNCTION:


Functions that calls itself is known as recursive.
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:
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact (5))
OUTPUT: 120

2. Explain the scope of variables with an example.


• Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can refer
(use) it.
• We can say that scope holds the current set of variables and their values.
• There are two types of scopes - local scope and global scope.
 Local Scope:
• A variable declared inside the function's body or in the local scope is known as local variable.

35
Rules of local variable:
• A variable with local scope can be accessed only within the function/block that it is created in.
• When a variable is created inside the function/block, the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal arguments are also local to function.
Example:
def loc():
y=0 # local scope
print(y)
loc()
Output: 0
 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/block.
 Rules of global Keyword
The basic rules for global keyword in Python are:
• 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 read and write a global variable inside a function.
• Use of global keyword outside a function has no effect
Use of global Keyword
• Without using the global keyword we cannot modify the global variable inside the function but we can
only access the global variable.
Example:
x=0
def add():
global x
x=x+5
add()
print ("Global X :", x)

Output:
Global X : 5
3. Explain the following built-in functions.
(a) id() (b) chr() (c) round() (d) type() (e) pow()

Function Description Syntax Example


id ( ) Return the “identity” of an id (object) x=15
object. i.e. the address of print ('address of x is :',id (x))
the object in memory. Output:
address of x is : 1357486752
chr ( ) Returns the Unicode c=65
character for the given chr(i) print(chr(c))
ASCII value. Output:
A

36
Returns the nearest
round ( ) integer to its input. round x= 17.9
1. First argument is used (number print (round (x))
to specify the value to be [,ndigits]) Output:
rounded. 18
2. Second argument is used
to specify the number of
decimal digits desired after
rounding.
Returns the type of object type (object) x= 15.2
type ( ) for the given single print (type (x))
object. Output:
<class 'float'>
Returns the computation pow (a,b) a= 5
pow ( ) of a,b i.e. (a**b ) a raised b= 2
to the power of b print (pow (a,b))
Output:
25
4. Write a Python code to find the L.C.M. of two numbers.
CODE:
x=int(input("Enter first number:"))
y=int(input("Enter second number:"))
if x>y:
min=x
else:
min=y
while(1):
if((min%x == 0) and (min % y == 0)):
print("LCM is:",min)
break
min=min+1
OUTPUT:
Enter first number:2
Enter second number:3
LCM is: 6
5. Explain recursive function with an example.
 Functions that calls itself is known as recursive.
 When a function calls itself is known as recursion.
 Recursion works like loop but sometimes it makes more sense to use recursion than loop.
 Imagine a process would iterate indefinitely if not stopped by some condition is known as infinite iteration.
 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.
 Python stops calling recursive function after certain limit by default.
 So, It also allows you to change the limit using sys.setrecursionlimit (limit_value).

37
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:
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120
8. STRINGS AND STRING MANIPULATION
Section – A
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) %f (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)
Section-B
Answer the following questions (2 Mark)
1. What is String?
 String is a data type in python, used to handle array of characters.
38
 String is a sequence of characters that may be a combination of letters, numbers, or special
symbols enclosed within single, double or even triple quotes.
2. Do you modify a string in Python?
 No we cannot modify the string in python.
 String is an immutable
3. How will you delete a string in Python?
 Python will not allow deleting a particular character in a string.
 Whereas you can remove entire string variable using del command.
 Example:
del str1[2]
4. What will be the output of the following python code?
str1 = “School”
print(str1*3)
OUTPUT:
School School School
5. What is slicing?
 Slice is a substring of a main string.
 A substring can be taken from the original string by using [ ] slicing operator and index or subscript values.
 Using slice operator, you have to slice one or more substrings from a main string.
Syntax: str[start:end]
Example: Str1[0:4
Section-C
Answer the following questions (3 Mark)
1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
CODE:
str="COMPUTER"
index=len(str)
for i in str:
print(str[:index])
index-=1
2. Write a short about the followings with suitable example: (a) capitalize( ) (b) swapcase( )
FUNCTION PURPOSE EXAMPLE
Used to capitalize the first character of the >>> city="chennai"
capitalize( ) string >>> print(city.capitalize())
Output:
Chennai

39
It will change case of every character to its >>> str1="tAmiL NaDu"
swapcase( ) opposite case vice-versa. >>> print(str1.swapcase())
Output:
TaMIl nAdU

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


CODE:
str1 = "welcome"
str2 = "to school"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
OUTPUT:
weol
4. What is the use of format( )? Give an example.
 The format( ) function used with strings is very powerful function used for formatting strings.
 The curly braces { } are used as placeholders or replacement fields which get replaced along with format
( ) function.
EXAMPLE:
x=3
y=5
print ("The sum of { } and { } is { }".format(x, y,(x+y)))
OUTPUT: The sum of 3 and 5 is 8
5. Write a note about count( ) function in python.
 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'))
OUTPUT: 2
Section - D
Answer the following questions: (5 Mark)
1. Explain about string operators in python with suitable example.
STRING OPERATORS
Python provides the following string operators to manipulate string.

(i) Concatenation (+)


 Joining of two or more strings using plus (+) operator is called as Concatenation.

40
Example
>>> "welcome" + "Python"
Output: 'welcomePython'

(ii) Append (+ =)
 Adding more strings at the end of an existing string using operator += is known as append.
Example:
>>> str1="Welcome to "
>>> str1+="Learn Python"
>>> print (str1)
Output: Welcome to Learn Python
(iii) Repeating (*)
 The multiplication operator (*) is used to display a string in multiple number of times.
Example:
>>> str1="Welcome "
>>> print (str1*4)
Output: Welcome Welcome Welcome Welcome
9. LISTS, TUPLES, SETS, AND DICTIONARY
Section – A
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.

41
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) :
Section-B
Answer the following questions (2 Mark)
1. What is List in Python?
 A list is an ordered collection of values enclosed within square brackets [ ] also known as a “sequence data
type”.
 Each value of a list is called as element.
 Elements can be a numbers, characters, strings and even the nested lists.
2. How will you access the list elements in reverse order?
 Python enables reverse or negative indexing for the list elements.
 A negative index can be used to access an element in reverse order.
 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.
3. What will be the value of x in following python code?
List1=[2,4,6,[1,3,5]]
x=len(List1)
print(x)
OUTPUT:
4
>>>

4. Differentiate del with remove( ) function of List.


del remove( )
del statement is used to delete known elements remove( ) function is used to delete elements of a
list if its index is unknown.
The del statement can also be used to delete The remove is used to delete a particular element
entire list.
5. Write the syntax of creating a Tuple with n number of elements.
Syntax:
Tuple_Name = (E1, E2, E2 ……. En) # Tuple with n number elements
Tuple_Name = E1, E2, E3 ….. En # Elements of a tuple without parenthesis
6. What is set in Python?
 In python, a set is another type of collection data type.
 A Set is a mutable and an unordered collection of elements without duplicates or repeated element.
 This feature used to include membership testing and eliminating duplicate elements.

42
Section-C
Answer the following questions (3 Mark)
1. What are the difference between List and Tuples?
 List  Tuples
 A list is an ordered collection of values  Tuples consists of a number of values separated
enclosed within square brackets [ ]. by comma and enclosed within Parentheses ( ).
 The elements in list are mutable.  The elements in Tuples are immutable.
 Iterating list is slower.  Iterating tuples is faster.
 Example:  Example:
 Var = [1,2,3]  Tup = (red, green, blue)
2. Write a short note about sort( ).
sort ( ):
 It sorts the element in the list.
 sort ( ) will affect the original list.
Syntax : List.sort(reverse=True|False, key=myFunc)
Description of the Syntax:
Both arguments are optional ,
 If reverse is set as True, list sorting is in descending order.
 Ascending is default.
 Key=myFunc; “myFunc” - the name of the user defined function that specifies the sorting criteria.
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.
del clear( )
The del statement is used to delete known elements The function clear( ) is used to delete all the
elements in list
The del statement can also be used to delete entire It deletes only the elements and retains the list.
list.
Example: Example:
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Age' : Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Age' :
18} 18}
del Dict['Age'] Dict.clear( )
print (Dict) print(Dict)
Output: {'Roll No' : 12001, 'SName' : 'Meena'} Output: { }
5. List out the set operations supported by python.
Set Operations:

(i) Union: 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.
43
6. What are the difference 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.
Section - D
Answer the following questions: (5 Mark)
1. What the different ways to insert an element in a list. Explain with suitable example.
Inserting elements in a list using insert():
 The insert( ) function is used to insert an element at desired position of a list.
Syntax:
List.insert (position index, element)
Example:
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar']
>>> MyList.insert(3, 'Rama')
>>> print(MyList)
Output: [34, 98, 47, 'Rama', 'Kannan', 'Gowrisankar']
th
 In the above example, insert( ) function inserts a new element ‘Rama’ at the index value 3, ie. at the 4
position.
 While inserting a new element, the existing elements shifts one position to the right.
Adding more elements in a list using append():
 The append( ) function is used to add a single element in a list.
 But, it includes elements at the end of a list.
Syntax:
List.append (element to be added)
Example:
>>> Mylist=[34, 45, 48]
>>> Mylist.append(90)
>>> print(Mylist)
Output: [34, 45, 48, 90]
Adding more elements in a list using extend():
 The extend( ) function is used to add more than one element to an existing list.
 In extend( ) function, multiple elements should be specified within square bracket as arguments of the
function.
Syntax:
List.extend ( [elements to be added])
Example:
>>> Mylist=[34, 45, 48]
>>> Mylist.extend([71, 32, 29])
44
>>> print(Mylist)
Output: [34, 45, 48, 90, 71, 32, 29]
2. What is the purpose of range( )? Explain with an example.
range():
 The range( ) is a function used to generate a series of values in Python.
 Using range( ) function, you can create list with series of values.
 The range( ) function has three arguments.
Syntax of range ( ) function:
range (start value, end value, step value)
where,
 start value – beginning value of series. Zero is the default beginning value.
 end value – upper limit of series. Python takes the ending value as upper limit – 1.
 step value – It is an optional argument, which is used to generate different interval of values.
Example : Generating whole numbers upto 10
for x in range (1, 11,2):
print(x)
Output:
1
3
5
7
9
Creating a list with series of values
 Using the range( ) function, you can create a list with series of values.
 To convert the result of range( ) function into list, we need one more function called list( ).
 The list( ) function makes the result of range( ) as a list.
Syntax:
List_Varibale = list ( range ( ) )
Example :
>>> Even_List = list(range(1,11,2))
>>> print(Even_List)
Output: [1, 3, 5, 7, 9]
 In the above code, list( ) function takes the result of range( ) as Even_List elements.
 Thus, Even_List list has the elements of first five even numbers.
3. What is nested tuple? Explain with an example.
Tuple:
 Tuples consists of a number of values separated by comma and enclosed within parentheses.
 Tuple is similar to list, values in a list can be changed but not in a tuple.
Nested Tuples:
 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.

45
Example:
Toppers = (("Vinodini", "XII", 98.7), ("Soundarya", "XII ", 97.5), ("Tharani", "XII ", 95.3), ("Saisri",
"XII ", 93.8))
for i in Toppers:
print(i)
Output:
('Vinodini', 'XII', 98.7)
('Soundarya', 'XII', 97.5)
('Tharani', 'XII', 95.3)
('Saisri', 'XII', 93.8)
4. Explain the different set operations supported by python with suitable example.
 A Set is a mutable and an unordered collection of elements without duplicates.
Set Operations:
 The set operations such as Union, Intersection, difference and Symmetric difference.
(i) Union:
 It includes all elements from two or more sets.
 The operator | is used to union of two sets.
 The function union( ) is also used to join two sets in python.

Example:
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
print(set_A|set_B)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
(ii) Intersection:
 It includes the common elements in two sets.
 The operator & is used to intersect two sets in python.
 The function intersection( ) is also used to intersect two sets in python.

Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}

46
print(set_A & set_B)
Output:
{'A', 'D'}
(iii) Difference:
 It includes all elements that are in first set (say set A) but not in the second set (say set B).
 The minus (-) operator is used to difference set operation in python.
 The function difference( ) is also used to difference operation.

Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
{2, 4}
(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.
 The caret (^) operator is used to symmetric difference set operation in python.
 The function symmetric_difference( ) is also used to do the same operation.

Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)
Output:
{2, 4, 'B', 'C'}
10. PYTHON CLASSES AND OBJECTS
Section – A
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
47
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
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
Section-B
Answer the following questions (2 Mark)
1. What is class?
 Class is the main building block in Python.
 Class is a template for the object.
 Objects are also called as instances of a class or class variable.
2. What is instantiation?
 The process of creating object is called as “Class Instantiation”.
 Objects are also called as instances of a class.
Syntax:
Object_name = class_name( )
3. What is the output of the following program?
class Sample:
num=10
def disp(self):
print(self. num)
S=Sample()
S.disp()
print(S. num)
OUTPUT:
>>>
10
line 7, in <module>
print(S. num)
AttributeError: 'Sample' object has no attribute ' num'

48
4. How will you create constructor in Python?
 “init” is a special function begin and end with double underscore in Python act as a Constructor.
 Constructor function will automatically executed when an object of a class is created.
General format:
def init (self, [args ........... ]):
<statements>
5. What is the purpose of Destructor?
 Destructor is also a special method gets executed automatically when an object exit from the scope.
 In Python, del ( ) method is used as destructor.
General format:
def del (self):
<statements>
Section-C
Answer the following questions (3 Mark)
1. What are class members? How do you define it?
 Variables defined inside a class are called as “Class Variable” and functions are called as “Methods”.
 Class variable and methods are together known as members of the class.
 The class members should be accessed through objects or instance of class.
 A class can be defined anywhere in a Python program.
CLASS DEFINITION:
class Sample:
x, y = 10, 20 #class variables
S=Sample( ) # class instantiation
print("Value of x = ", S.x)
print("Value of y = ", S.y)
2. Write a class with two private class variables and print the sum using a method.
CODE:
class Sample:
def init (self,n1,n2):
self. n1=n1
self. n2=n2
def sum(self):
print("Class Variable 1:",self. n1)
print("Class Variable 2:",self. n2)
print("Sum:",self. n1 + self. n2)
S=Sample(5,10)
S.sum()
OUTPUT:
>>>
Class Variable 1: 5
Class Variable 2: 10
Sum: 15
>>>

49
3. Find the error in the following program to get the given output?
ERROR CODE:
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:
line 8, in <module>
del F.display
AttributeError: display
CORRECT CODE:
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')
F.display()
OUTPUT:
Fruit 1 = Apple, Fruit 2 = Mango
4. What is the output of the following program?
CODE:
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
>>>

50
5. How do define constructor and destructor in Python?
CONSTRUCTOR:
 “init” is a special function begin and end with double underscore in Python act as a Constructor.
 Constructor function will automatically executed when an object of a class is created.
General format of constructor:
def init (self, [args ........... ]):
<statements>
DESTRUCTOR:
 Destructor is also a special method gets executed automatically when an object exit from the scope.
 In Python, del ( ) method is used as destructor.
General format of destructor:
def del (self):
<statements>
Section - D
Answer the following questions: (5 Mark)
1. Explain about constructor and destructor with suitable example
Constructor:
 Constructor is the special function called “init” which act as a Constructor.
 This function will executes automatically when the object is created.
 It must begin and end with double underscore.
 It can be defined with or without arguments.
General format:
def init (self, [args .......... ]):
<statements>
Destructor:
 Destructor is also a special method gets executed automatically when an object exit from the scope.
 del ( ) method is used as destructor.
General format:
def del (self):
<statements>
Example:
class Sample:
def init (self, num):
print("Constructor of class Sample...")
self.num=num
print("The value is :", num)
def del (self):
print("Constructor of class Sample...")
S=Sample(10)
 The class “Sample” has a constructor which executed automatically, when an object S is created with
actual parameter 10..
 When the constructor gets executed, it prints the “Constructor of class Sample….”,
 The passing value of the constructor is assigned to self.num and it prints the value passed.
 Finally the destructor executed and it prints the statement given.
51
OUTPUT:
Constructor of class Sample...
The value is : 10
Destructor of class Sample...
11. DATABASE CONCEPTS
Section – A
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
Section-B
Answer the following questions (2 Mark)
1. Mention few examples of a database.
 Foxpro
 dbase.
 IBM DB2.
2. List some examples of RDBMS.
 Microsoft Access
 SQL Server
 Oracle
 MySQL
 MariaDB
 SQLite
3. What is data consistency?
 Data Consistency means that data values are the same at all instances of a database.
 On live data, it is being continuously updated and added, maintaining the consistency of data can
become a challenge.
 But DBMS handles it by itself.

52
4. What is the difference between Hierarchical and Network data model?
Hierarchical data model Network data model
 In hierarchical model, a child record has only  In a Network model, a child may have many
one parent node parent nodes.

 It represents one-to-many relationship called  It represents the data in many-to-many


parent-child relationship in the form of tree relationships.
structure.
5. What is normalization?
 Normalization is an integral part of RDBMS in order to reduce data redundancy and improve data
integrity.
Section-C
Answer the following questions (3 Mark)
1. What is the difference between Select and Project command?
Select Command Project Command
 The SELECT operation is used for selecting a  The projection method defines a relation that
subset with tuples according to a given contains a vertical subset of Relation.
condition C.
 Select filters out all tuples that do not satisfy C.  The projection eliminates all attributes of the
input relation but those mentioned in the
projection list.
Symbol : Symbol :
σ Π
General Form: Example:
σ (R)
c
Π (STUDENT)
Example: course
σ = “Big Data” (STUDENT )
course
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.
 This type of operation is helpful to merge columns from two relations.
 Example: A x B means A times B, where the relation A and B have different attributes.
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.
 It is used in file Management System.
 It represents real world objects, attributes and behaviors.

53
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.
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:
 They are responsible for identifying the data to be stored in the database for choosing appropriate structures
to represent and store the data.
Section - D
Answer the following questions: (5 Mark)
1. Explain the different types of data model.
Data Model
A data model describes how the data can be represented and accessed from a software after complete
implementation
Types of Data Model
The different types of a Data Model are,
 Hierarchical Model
 Relational Model
 Network Database Model
 Entity Relationship Model
 Object Model
i). Hierarchical Model:
 In Hierarchical model, data is represented as a simple tree like structure form.
 This model represents a one-to-many relationship ie 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.
 Example:

54
ii). Relational Model
 The Relational Database model was first proposed by E.F. Codd in 1970 .
 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.
 Hence tables are also known as relations in a relational model.
 A relation key is an attribute which uniquely identifies a particular tuple (row in a relation (table)).

 Example:

iii.) Network Model


 Network database model is an extended form of hierarchical data model.
 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.

iv.) Entity Relationship Model. (ER model)


 In this database model, relationship are created by dividing the object into entity and its characteristics into
attributes.
 It was developed by Chen in 1976.
 ER model constructed by,
 Rectangle represents the entities.
 Ellipse represents the attributes .
 Attributes describes the characteristics and each entity.
 Diamond represents the relationship in ER diagrams
 Example: Doctor diagnosis the Patient.

v.) 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.

55
Example:

2. Explain the different types of relationship mapping.


Types of Relationships : There are the types of relationships used in a database.
1. One-to-One Relationship
2. One-to-Many Relationship
3. Many-to-One Relationship
4. Many-to-Many Relationship
i.) One-to-One Relationship:
 In One-to-One Relationship, one entity is related with only one other entity.
 One row in a table is linked with only one row in another table and vice versa.
 For Example: A student can have only one exam number.

ii. One-to-Many Relationship:


 In One-to-Many relationship, one entity is related to many other entities.
 One row in a table A is linked to many rows in a table B, but one row in a table B is linked to only one
row in table A.
 For Example: One Department has many staff members.

iii. Many-to-One Relationship:


 In Many-to-One Relationship, many entities can be related with only one in the other entity.
 For Example: A number of staff members working in one Department.
 Multiple rows in staff members table is related with only one row in Department table.

56
4. Many-to-Many Relationship:
 A many-to-many relationship occurs when multiple records in a table are associated with multiple
records in another table.
 Example: Books and Student :Many Books in a Library are issued to many students.

3. Differentiate DBMS and RDBMS.


Basis of Comparison DBMS RDBMS
Expansion Database Management System Relational DataBase Management
System
Data storage Navigational model Relational model (in tables). ie data
ie data by linked records in tables as row and column
Data redundancy Exhibit Not Present
Normalization Not performed RDBMS uses normalization to
reduce redundancy
Data access Consumes more time Faster, compared to DBMS.
Keys and indexes Does not use. Used to establish relationship. Keys
are used in RDBMS.
Transaction management Inefficient, Efficient and secure.
Error prone and insecure.
Distributed Databases Not supported Supported by RDBMS.
Example Dbase, FoxPro. SQL server, Oracle, mysql,
MariaDB, MS-Access, SQLite.
4. Explain the different operators in Relational algebra with suitable examples.
 Relational Algebra is used for modeling data stored in relational databases and for defining queries on it.
 Relational Algebra is divided into various groups.
1) Unary Relational Operations
 SELECT ( symbol : σ)
 PROJECT ( symbol : Π)
2) Relational Algebra Operations from Set Theory
 UNION (∪)
 INTERSECTION (∩)
 DIFFERENCE (−)
57
 CARTESIAN PRODUCT (X)
 SELECT (symbol : σ)
 General form σ ( R ) with a relation R and a condition C on the attributes of R.
c

 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.
 Example: σ = “Big Data” (STUDENT )
course
 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: Π (STUDENT)
course
 UNION (Symbol :∪) A U B
 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
 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.
 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.
 PRODUCT OR CARTESIAN PRODUCT (Symbol : X )
 Cross product is a way of combining two relations.
 The resulting relation contains, both relations being combined.
 This type of operation is helpful to merge columns from two relations.
 A x B means A times B, where the relation A and B have different attributes.

5. Explain the characteristics of RDBMS.


 RDBMS provides the facility to manipulate data (store,
1. Ability to manipulate data modify, and delete) in a database.
 Unnecessary repetition of data in database was a big problem.
2. Reduced Redundancy  RDBMS follows Normalisation which divides the data in
such a way that repetition is minimum.
 Data Consistency means that data values are the same at all
3.Data Consistency
instances of a database.
 RDBMS allows multiple users to work on it(update, insert,
4.Support Multiple user and
delete data) at the same time and still manages to maintain the
Concurrent Access
data consistency.
 RDBMS provides users with a simple query language, using
which data can be easily fetched, inserted, deleted and updated
5.Query Language in a database.

58
 The RDBMS also takes care of the security of data, protecting
the data from unauthorized access.
6. Security
 Creating user accounts with different access permissions we
can easily secure our data.
7. DBMS Supports  It allows us to better handle and manage data integrity in real
Transactions world applications where multi-threading is extensively used.
12. STRUCTURED QUERY LANGUAGE
Section – A
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 including the structure 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
Section-B
Answer the following questions (2 Mark)
1. Write a query that selects all students whose age is less than 18 in order wise.
Query: SELECT * FROM Student WHERE Age<=18 ORDER BY Name;
2. Differentiate Unique and Primary Key constraint.
Unique Key Constraint Primary Key Constraint
 This constraint ensures that no two rows have  This constraint declares a field as a Primary key
the same value in the specified columns. which helps to uniquely identify a record.
 The UNIQUE constraint can be applied only to  The primary key field must have the NOT NULL
fields that have also been declared as NOT constraint.
NULL.
3. Write the difference between table constraint and column constraint?
Table Constraint Column Constraint
 Table constraints apply to a group of one or  Column constraints apply only to individual
more columns. column.

4. Which component of SQL lets insert values in tables and which lets to create a table?
Command Description component
Insert Inserts data into a table DML
Create To create tables in the database. DDL

5. What is the difference between SQL and MySQL?


SQL MySQL
 Structured Query Language is a language  MySQL is a database management system, like
used for accessing databases. SQL Server, Oracle, Informix, Postgres, etc.
 SQL is a DBMS  MySQL is a RDBMS.

59
Section-C
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.
 Primary 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 field must have the NOT NULL constraint.
2. Write a SQL statement to modify the student table structure by adding a new field.
Syntax : ALTER TABLE <table-name> ADD <column-name><data type><size>;
To add a new column “Address” of type ‘char’ to the Student table, the command is used as
Statement: ALTER TABLE Student ADD Address char;
3. Write any three DDL commands.
Data Definition Language:
Create Command: To create tables in the database.
CREATE TABLE Student (Admno integer, Name char(20));
Alter Command: Alters the structure of the database.
ALTER TABLE Student ADD Address char;
Drop Command: Delete tables from database.
DROP TABLE Student;
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: SAVEPOINT A;
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.
 This helps to eliminate redundant data.
 For Example: SELECT DISTINCT Place FROM Student;
Section - D
Answer the following questions: (5 Mark)
1. Write the different types of constraints and their functions.
 Constraint is a condition applicable on a field or set of fields.
Type of Constraints:

Table Constraint
(i) Unique Constraint:
 This constraint ensures that no two rows have the same value in the specified columns.

60
 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:
 The UNIQUE constraint can be applied only to fields that have also been declared as NOT NULL.
 When two constraints are applied on a single field, it is known as multiple constraints.
(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 must have the NOT NULL constraint.
(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.
(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.
 Let us take a new table namely Student1 with the following fields Admno, Firstname, Lastname, Gender,
Age, Place:
 Example:
CREATE TABLE Student
(
Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint
Exam no integer NOT NULL UNIQUE, → Unique constraint
Name char(20)NOT NULL,
Gender char(1) DEFAULT = “M”, → Default Constraint
Age integer (CHECK<=19), → Check Constraint
);
2. Consider the following employee table. Write SQL commands for the qtns.(i) to (v).

(i) To display the details of all employees in descending order of pay.


SELECT * FROM employee ORDER BY DESC;
(ii) To display all employees whose allowance is between 5000 and 7000.
SELECT * FROM employee WHERE allowance BETWEEN 5000 AND 7000;

61
(iii) To remove the employees who are mechanic.
DELETE FROM employee WHERE desig=’Mechanic’;
(iv) To add a new row.
INSERT INTO employee
(empcode,name,desig,pay,allowance)VALUES(S1002,Baskaran,Supervisor,29000,12000);
(v) To display the details of all employees who are operators.
SELECT * FROM employee WHERE design=’Operator’;
3. What are the components of SQL? Write the commands in each.
Components of SQL:

i) DATA MANIPULATION LANGUAGE :


 A Data Manipulation Language (DML) is a computer programming language used for adding (inserting),
removing (deleting), and modifying (updating) data in a database.
 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.

ii) 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.
 The DDL provides a set of definitions to specify the storage structure and access methods used by the
database system.
 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.
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).

62
 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.
4. Construct the following SQL statements in the student table:
(i) SELECT statement using GROUP BY clause.
 The GROUP BY clause is used with the SELECT statement to group the students on rows or
columns having identical values or divide the table in to groups.
QUERY: SELECT Gender FROM Student GROUP BY Gender;
Output:
Gender
Male
Female
QUERY: SELECT Gender, count(*) FROM Student GROUP BY male;
Output:
Gender Count(*)
Male 5
Female 3

(ii) SELECT statement using ORDER BY clause.


 The ORDER BY clause is used to display the list in ascending or descending order.
QUERY: SELECT * FROM student WHERE Age>=18 ORDER BY Name DESC;
Output:

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
(
empno integer NOT NULL,
name char(20),
63
desig char(20),
pay integer,
allowance integer,
PRIMARY KEY (empno)
);
13. PYTHON AND CSV FILES
Section – A
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. 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
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator = '\n')
with open('c:\pyprg\ch13\line2.csv', 'w') as f:
wr = csv.writer(f,dialect='M')
wr.writerows(D)
f.close()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
(C) E (D) Exam,
Q Quarterly,
H Halfyearly

64
Section-B
Answer the following questions (2 Mark)
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.
 A CSV file is also known as a Flat File that can be imported and store data in tables, such as Microsoft
Excel or OpenOfficeCalc.
2. Mention the two ways to read a CSV file using Python.

3. Mention the default modes of the File.


 The default is reading (‘r’) in text mode.
 The default Open in (‘t’) text mode.
4. What is use of next() function?
 “next()”command is used to avoid or skip the first row or row heading.
 Example: While sorting the row heading is also get sorted, to avoid that the first is skipped using next().
 Then the list is sorted and displayed.
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.
Syntax: operator.itemgetter(col_no)
Example: sortedlist = sorted (data, key=operator.itemgetter(1))
Section-C
Answer the following questions (3 Mark)
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.
 The two methods are,
 f = open("test.txt")  This 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.
with open("test.txt",’r’) as f:  This method ensures that the file is closed when the block inside with is
exited.
2. Write a Python program to modify an existing file.
 In this program, the third row of “student.csv” is modified and saved.
 First the “student.csv” file is read by using csv.reader() function.
 Then, the list() stores each row of the file.
 The statement “lines[3] = row”, changed the third row of the file with the new content in “row”.
 The file object writer using writerows (lines) writes the values of the list to “student.csv” file.
PROGRAM: student.csv
import csv
row = [‘3’, ‘Meena’,’Bangalore’]
with open(‘student.csv’, ‘r’) as readFile:
reader = csv.reader(readFile)
65
lines = list(reader)
lines[3] = row
with open(‘student.csv’, ‘w’) as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)
readFile.close()
writeFile.close()
3. Write a Python program to read a CSV file with default delimiter comma (,).
Program:
import csv
with open('c:\\pyprg\\sample1.csv', 'r') as F:
reader = csv.reader(F)
print(row)
F.close()
OUTPUT:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']
4. What is the difference between the write mode and append mode.
Write Mode Append Mode
 'w'  'a'
 Open a file for writing.  Open for appending at the end of the file
without truncating it.
 Creates a new file if it does not exist or  Creates a new file if it does not exist.
truncates the file if it exists.
5. What is the difference between reader() and DictReader() function?
Reader():
 The reader function 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 (,).
 csv. Reader work with list/tuple.DictReader():
 DictReader works by reading the first line of the CSV and using each comma separated value in this line
as a dictionary key.
 DictReader is a class of csv module is used to read a CSV file into a dictionary.
 It creates an object which maps data to a dictionary.
 csv.DictReader work with dictionary.
Section - D
Answer the following questions: (5 Mark)
1. Differentiate Excel file and CSV file.
Excel CSV
 Excel is a binary file that holds information about  CSV format is a plain text format with a series
all the worksheets in a file, including both content of values separated by commas.
and formatting.

66
 CSV can be opened with any text editor in
 XLS files can only be read by applications that Windows like notepad, MS Excel, OpenOffice,
have been especially written to read their format, etc.
and can only be written in the same way.
 CSV is a format for saving tabular information
 Excel is a spreadsheet that saves files into its own into a delimited text file with extension .csv
proprietary format viz. xls or xlsx
 Importing CSV files can be much faster, and it
 Excel consumes more memory while importing also consumes less memory
data

2. Tabulate the different mode with its meaning.


Python File Modes:
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'  Opren 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.
Read a CSV File Using Python:
There are two ways to read a CSV file.
1. Use the csv.reader() method.
2. Use the DictReader class.
Reader Function:
 You can read the contents of CSV file with the help of csv.reader() method.
 The reader function is designed to take each line of the file and make a list of all columns. Then, you
just choose the column you want the variable data for.
 Using this method one can read data from csv files of different formats like quotes (" "), pipe (|) and
comma (,).
 csv. reader and csv.writer work with list/tuple
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 dilects like , | etc can be omitted
 fmtparams: optional parameter which help to override the default values of the dialects can be omitted.
Example:
import csv
F = ('c:\pyprg\sample1.csv', 'r')
reader = csv.reader(F)
for row in reader:
print(row)
67
F.close()

68
DictReader class:
 To read a CSV file into a dictionary can be done by using DictReader class of csv Module.
 It works similar to the reader() class but 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 (i.e. fieldname).
 csv.DictReader work with dictionary.
 csv.DictReader take additional argument field names that are used as dictionary keys.
Example:
import csv
filename = ‘c: \pyprg\sample1.csv’
input_file =csv.DictReader(open(filename,’r’))
for row in input_file:
print(dict(row))
4. Write a Python program to write a CSV File with custom quotes.
import csv
info = [[‘SNO’, ‘Person’, ‘DOB’],
[‘1’, ‘Madhu’, ‘18/12/2001’],
[‘2’, ‘Sowmya’,’19/2/1998’],
[‘3’, ‘Sangeetha’,’20/3/1999’],
[‘4’, ‘Eshwar’, ‘21/4/2000’],
[‘5’, ‘Anand’, ‘22/5/2001’]]
csv.register_dialect(‘myDialect’,quoting=csv.QUOTE_ALL)
with open(‘c:\\pyprg\\ch13\\person.csv’, ‘w’) as f:
writer = csv.writer(f, dialect=’myDialect’)
for row in info:
writer.writerow(row)
f.close()
OUTPUT :
“SNO”,”Person”,”DOB”,”1”,”Madhu”,”18/12/2001”,”2”,”Sowmya”,”19/2/1998””3”,”Sangeetha”,”20/3/1999
” ”4”,”Eshwar”,”21/4/2000”,“5”,”Anand”,”22/5/2001”
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:

2. The last record in the file may or may not have an ending line break.
For example:

3. There may be an optional header line appearing as the first line of the file with the same format as normal
record lines.

69
 The header will contain names corresponding to the fields in the file and should contain the same number
of fields as the records in the rest of the file.
 For example: field_name1,field_name2,field_name3

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:

6. Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes.
 For example:

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:

14. IMPORTING C++ PROGRAMS IN PYTHON


Section – A
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

70
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
Section-B
Answer the following questions (2 Mark)
1. What is the theoretical difference between Scripting language and other programming language?
Scripting Language Programming Language
A scripting language requires an interpreter. A programming language requires a compiler.
A scripting language need not be compiled. A programming languages needs to be compiled
before running .
Example: Example:
JavaScript, VBScript, PHP, Perl, Python, Ruby, C, C++, Java, C# etc.
ASP and Tcl.
2. Differentiate compiler and interpreter.
Compiler Interpreter
Compiler generates an Intermediate Code. Interpreter generates Machine Code.
Compiler reads entire program for compilation. Interpreter reads single statement at a time for
interpretation.
Error deduction is difficult Error deduction is easy
Example: Example:
gcc, g++, Borland TurboC Python, Basic, Java

3. Write the expansion of (i) SWIG (ii) MinGW


SWIG - Simplified Wrapper Interface Generator - Both C and C++
MinGW - Minimalist GNU for Windows
4. What is the use of modules?
 Modules are used to break down large programs into small manageable and organized files.
 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.
 Syntax: cd <absolute path>
 “cd” command used to change directory and absolute path refers to the complete path where Python is
installed.
Example: c:\>cd\ myfiles
Section-C
Answer the following questions (3 Mark)
1. Differentiate PYTHON and C++.
PYTHON C++
 Python is typically an "interpreted" language  C++ is typically a "compiled" 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
71
 It is a general purpose language
 It can act both as scripting and general purpose
language

2. What are the applications of scripting language?


 To automate certain tasks in a program
 Extracting information from a data set
 Less code intensive as compared to traditional programming language
 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.
 It is used in compiling and linking the code of C, C++ and FORTRAN to be run on Windows Operating
System.
 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()
Welcome  Module name
.  Dot operator
display()  Function call
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 along via the command-line input, it's basically an array holding the
command-line arguments of the program.
 To use sys.argv, you will first have to import sys.
 sys.argv[0] is always the name of the program as it was invoked.
 sys.argv[1] is the first argument you pass to the program.
Section - D
Answer the following questions: (5 Mark)
1. Write any 5 features of Python.
 Python uses Automatic Garbage Collection.
 Python is a dynamically typed language.
 Python runs through an interpreter.
 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.
 In Python, a function may accept an argument of any type, and return multiple values without any kind of
declaration beforehand.
2. Explain each word of the following command.
COMMAND: Python <filename.py> -<i> <C++ filename without cpp extension>
Where ,
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 Name of C++ file to be compiled and executed
extension>

72
3. What is the purpose of sys, os, getopt module in Python. Explain
(i) Python’s sys Module:
 This module provides access to some variables used by the interpreter and to functions that interact
strongly with the interpreter.
 sys.argv is the list of command-line arguments passed to the Python program.
 argv contains all the items that come along via the command-line input, it's basically an array holding the
command-line arguments of the program.
 To use sys.argv, you will first have to import sys.
 sys.argv[0] is always the name of the program as it was invoked.
 sys.argv[1] is the first argument you pass to the program.
(ii) 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.
 os.system(): Execute the C++ compiling command in the shell.
 For Example to compile C++ program g++ compiler should be invoked.
 Command: os.system (‘g++’ + <varaiable_name1> ‘-<mode>’ + <variable_name2>
 Example:
os.system('g++ ' + cpp_file + ' -o ' + exe_file) -- g++ compiler compiles the file cpp_file and –o
(output) send to exe_file
(iii) Python getopt Module:
 The getopt module of Python helps you to parse (split) command-line options and arguments.
 This module provides two functions to enable command-line argument parsing.
 getopt.getopt method:
 This method parses command-line options and parameter list.
 Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
 Here is the detail of the parameters −
 argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
 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 parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('=').
 In our program the C++ file name will be passed as string and ‘i’ also will be passed along with to
indicate it as the input file.
 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, path and args contains any string if at all not splitted
because of wrong path or mode.
 args will be an empty array if there is no error in splitting strings by getopt().

73
4. Write the syntax for getopt() and explain its arguments and return values.
Python getopt Module:
 The getopt module of Python helps you to parse (split) command-line options and arguments.
 This module provides two functions to enable command-line argument parsing.
 getopt.getopt method:
 This method parses command-line options and parameter list.
 Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
 Here is the detail of the parameters −
 argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
 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 parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('=').
 In our program the C++ file name will be passed as string and ‘i’ also will be passed along with to
indicate it as the input file.
 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, path and args contains any string if at all not splitted
because of wrong path or mode.
 args will be an empty array if there is no error in splitting strings by getopt().
 Example:
 opts, args = getopt.getopt (argv, "i:",['ifile='])
5. Write a Python program to execute the following c++ coding.
C++ CODE:
#include <iostream>
using namespace std;
int main()
{ cout<<“WELCOME”;
return(0);
}
The above C++ program is saved in a file welcome.cpp
PYTHON PROGRAM:
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'

74
exe_file = a + '.exe'
run(cpp_file, exe_file)
def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
os.system('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print(" ")
print
os.system(exe_file)
print
if name ==' main ': #program starts executing from here
main(sys.argv[1:])
STEPS TO IMPORT CPP CODE INTO PYTHON CODE:
 Select File→New in Notepad and type the above Python program.
 Save the File as welcome.py.
 Click the Run Terminal and open the command window
 Go to the folder of Python using cd command.
 Type the command: Python c:\pyprg\welcome.py -i c:\pyprg\welcome_cpp
OUTPUT:

WELCOME

15. DATA MANIPULATION THROUGH SQL


Section – A
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 clause avoide the duplicate?
(A) Distinct (B) Remove (C) Where (D) GroupBy
75
Section-B
Answer the following questions (2 Mark)
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.
 Create a connection using connect () method and pass the name of the database File.
 Example:
import sqlite3
connection = sqlite3.connect ("Academy.db")
cursor = connection.cursor()
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:
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average, birth_date)
VALUES (NULL, "Akshay", "B", "M","87.8", "2001-12-12");"""
cursor.execute(sql_command)
5. Which method is used to fetch all rows from the database table?
 The fetchall() method is used to fetch all rows from the database table.
 Example:
cursor.execute("SELECT * FROM student")
print(cursor.fetchall())
Section-C
Answer the following questions (3 Mark)
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:
 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()
 The fetchone() method returns the next row of a  The fetchmany() method returns the next
query result set or None in case there is no row number of rows (n) of the result set.
left
 Using while loop and fetchone() method we can  Displaying specified number of records is done
display all the records from a table. by using fetchmany().

76
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 fulfill a specified condition.
EXAMPLE: To display the different grades scored by male students from “student table”
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT:
('B',)
('A',)
('C',)
('D',)
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”)
c=conn.execute(“SELECT * FROM Employee GROUP BY Dept”)
for row in c:
print(row)
conn.close()
5. Read the following details.Based on that write a python script to display records in
desending 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(“SELECT * FROM Employee ORDER BY Eno DESC”)
result=cursor.fetchall()
print(result)
Section - D
Answer the following questions: (5 Mark)
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.

77
 It is designed to be embedded in applications, instead of using a separate database server program such as
MySQLor Oracle.
ADVANTAGES:
 SQLite is fast, rigorously tested, and fl exible, making it easier to work.
 Python has a native library for SQLite.
Steps To Use SQLite:
Step 1: import sqlite3
Step 2: Create a connection using connect () method and pass the name of the database File
 Connecting to a database in step2 means passing the name of the database to be accessed.
 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 ()
 Cursor is a control structure used to traverse and fetch the records of the database.
 Cursor has a major role in working with Python.
 All the commands will be executed using cursor object only.
 To create a table in the database, create an object and write the SQL command in it.
Example:-
import sqlite3
connection=sqlite3.connect("organization.db")
cursor=connection.cursor( )
 For executing the command use the cursor method and pass the required sql command as a parameter.
 Many number of commands can be stored in the sql_comm and can be executed one after other.
 Any changes made in the values of the record should be saved by the commend "Commit" before closing
the "Table connection".
2. 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

PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“Materials.db”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Materials”)
print(“Displaying All The Records”)
result=cursor.fetchmany(5)
print(result, Sep= “\n”)

78
OUTPUT:
Displaying All The Records
(1003, ‘Scanner’, 10500)
(1004, ‘Speaker’, 3000)
(1005, ‘Printer’, 8000)
(1008, ‘Monitor’, 15000)
(1010, ‘Mouse’, 700)
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 :- Item Name :-
Rate :- Integer
Record to be added :- 1008, Monitor,15000

PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor=connection.cursor()
sql_command – “““ CREATE TABLE Item(
Icode INTEGER PRIMARY KEY,
ItemName VARCHAR(25),
Rate INTEGER) ; ”””
cursor.execute(sql_command)
sql_command = “““ INSERT INTO Item(Icode, ItemName, Rate) VALUES (1008, ‘Monitor’, 15000);
”””
79
cursor.execute(sql_command)
connection.commit()
connection.close()
print(“TABLE CREATED”)
OUTPUT:
TABLE CREATED
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
PYTHON SCRIPT:
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“SELECT Supplier.Name, Supplier.City,Item.ItemName FROM Supplier,Item
WHERE Supplier.Icode = Item.Icode AND Supplier.City NOT In Delhi ”)
s = [i[0] for I in cursor.description]
print(s)
result = cursor.fetchall()
for r in result:
print r
OUTPUT:
[‘Name’, ‘City’, ‘ItemName’]
[‘Anu’, ‘Bangalore’, ‘Scanner’]
[‘Shahid’, ‘Bangalore’, ‘Speaker’]
[‘Akila’, ‘Hyderabad’, ‘Printer’]
[‘Girish’, ‘Hyderabad’, ‘Monitor’]
[‘Shylaja’, ‘Chennai’, ‘Mouse’]
[‘Lavanya’, ‘Mumbai’, ‘CPU’]
ii) Increment the SuppQty of Akila by 40
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“UPDATE Supplier ST SuppQty = SuppQty +40 WHERE Name = ‘Akila’ ”)
cursor.commit()
result = cursor.fetchall()
print (result)
connection.close()

80
OUTPUT:
(S004, ‘Akila’, ‘Hyderabad’, 1005, 235)
16. DATA VISUALIZATION USING PYPLOT: LINE CHART, PIE CHART AND
BAR CHART
Section – A
Choose the best answer (1 Mark)
1. Which is a python package used for 2D graphics?
a. matplotlib.pyplot b. matplotlib.pip c. matplotlib.numpy d. matplotlib.plt
2. Identify the package manager for installing 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 a collection of resources assembled to create a single unified visual display.
a. Interface b. Dashboard c. Objects d. Graphics
5. Which of the following modules should be imported to visualize data and information in python?
a. csv b. getopt 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. Line chart b. Pie chart c. Bar chart d. All the above
7. Read the code:
a. import matplotlib.pyplot as plt
b. plt.plot(3,2)
c. plt.show()
Identify the output for the above coding.

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 intervas 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
Section-B
Answer the following questions (2 Mark)
1. Define: Data Visualization.
 Data Visualization is the graphical representation of information and data.

81
 The objective of Data Visualization is to communicate information visually to users using statistical
graphics.
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?
 Matplotlib can be installed using pip software.  python -m pip install -U matplotlib
 Pip is a management software for installing python packages.
 Importing Matplotlib using the command: import matplotlib.pyplot as plt
 Matplotlib can be imported in the workspace.
5. Write the difference between the following functions:
plt.plot([1,2,3,4]), plt.plot([1,2,3,4], [1,4,9,16]).

plt.plot([1,2,3,4]) plt.plot([1,2,3,4], [1,4,9,16])

It refers y value as [1,2,3,4] It refers x and y values as ([1,2,3,4], [1,4,9,16])

Indirectly it refers x values as [0,1,2,3] Directly x and y values are given as


(0,1) (1,1) (2,3) (3,4) (1,1) (2,4) (3,9) (4,16)
Answer the following questions (3 Mark)
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')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()

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

Program:
import matplotlib.pyplot as plt
slices=[29.2,8.3,8.3,54.2]
activities=['sleeping','eating', 'working','playing']
cols=['c','m','r','b']
plt.pie(slices, labels=activities, colors=cols,startangle=90, shadow=True,
explode=(0,0.1,0,0),autopct='%.2f')
plt.title('Interesting Graph \n Check it out')
plt.show()

83
Section - D
Answer the following questions: (5 Mark)
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.
 A Line Chart is often used to visualize a trend in data over intervals of time – a time series – thus the line
is often drawn chronologically.
 Example:

Bar Chart:
 A BarPlot (or BarChart) is one of the most common type of plot.
 It shows the relationship between a numerical variable and a categorical variable.
 Bar chart represents categorical data with rectangular bars.
 Each bar has a height corresponds to the value it represents.
 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:

Pie Chart:
 Pie Chart is probably one of the most common type of chart.
 It is a circular graphic which is divided into slices to illustrate numerical proportion.

84
 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 using the Python string formatting.
Example:

2. Explain the various buttons in a matplotlib window.

Home Button:
 The Home Button will help once you have begun navigating your chart.
 If you ever want to return back to the original view, you can click on this.
Forward/Back Buttons:
 These buttons can be used like the Forward and Back buttons in your browser.
 You can click these 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.

85
3. Explain the purpose of the following functions:
a. plt.xlabel
plt.xlabel()specifies label for X-axis
b. plt.ylabel
plt.ylabel()specifies label for Y-axis
c. plt.title
plt.title() specifies title to the graph
d. plt.legend()
Calling legend() with no arguments automatically fetches the legend handles and their associated labels.
e. plt.show()
Display a figure. When running in Python with its Pylab mode, display all figures and return to the
Python prompt.

86
HIGHER SECONDARY – SECOND YEAR
PRACTICAL MANUAL
GENERAL INSTRUCTIONS:
1. Eight Exercises from Python and Two from MySQL are practiced in the practical classes.
2. One question from python with internal choice.
3. Distribution of Marks as follows:
Duration of Practical: 2½ Hrs Maximum Marks: 20
I. INTERNAL ASSESSMENT: 5 MARKS
Record Book 5 Marks
II. EXTERNAL ASSESSMENT: 15 MARKS
Writing Code 10 Marks
Execution 5 Marks
TOTAL 20 Marks

LIST OF SOFTWARES:
1. PYTHON - 3.7.4 Version (or) Any Version
2. WAMP (or) XAMPP SERVER Any Version
3. MS-EXCEL
4. PIP
SOFTWARE INSTALLATION LINK:
1. PYTHON INSTALLATION, https://youtu.be/ozAVCkovZ4M

2. XAMPP SERVER INSTALLATION, https://youtu.be/lKqOpfPWlyY

3. PIP COMMAND
 Open Command Prompt, Type the command given below.
 python -m pip install -U pip
 pip install matplotlib

87
INDEX

QUESTION
SL.NO PROGRAM NAME
NUMBER

(a) CALCULATE FACTORIAL


1 PY 1
(b) SUM OF SERIES
(a) ODD OR EVEN
2 PY 2
(b) REVERSE THE STRING

GENERATE VALUES AND REMOVE ODD NUMBERS


3 PY 3

GENERATE PRIME NUMBERS AND SET OPERATIONS


4 PY 4

DISPLAY A STRING ELEMENTS – USING CLASS


5 PY 5

MYSQL – EMPLOYEE TABLE


6 DB 6

MYSQL – STUDENT TABLE


7 DB 7

PYTHON WITH CSV


8 PY 8

PYTHON WITH SQL


9 PY 9

PYTHON GRAPHICS WITH PIP


10 PY 10

88
PY 1(a) - CALCULATE FACTORIAL
QUESTION:
Write a program to calculate the factorial of the given number using for loop (Don’t use
built-in function factorial)
AIM:
To calculate the factorial of the given number using for loop.
CODING:
num = int(input("Enter the number:"))
fact = 1
for i in range(1, num+1):
fact = fact*i
print("Factorial of ", num," is", fact)

OUTPUT:

Enter a Number: 5
Factorial of 5 is 120

RESULT:

Thus the Python program to calculate factorial has been done and the output is verified.

89
PY 1(b) - SUM OF SERIES
QUESTION:
Write a program to sum the series: 1/1 + 22/2 + 33/3 + ……. nn/n
AIM:
To calculate the sum of the series: 1/1 + 22/2 + 33/3 + ……. nn/n
CODING:
n= int(input("Enter a value of n:"))
s=0
for i in range(1,n+1):
a=(i**i)/i
s=s+a
print("The sum of the series is", s)

OUTPUT:
Enter a value of n: 4
The sum of the series is 76.0

RESULT:
Thus the Python program to sum of series has been done and the output is verified.

90
PY 2(a) - ODD OR EVEN
QUESTION:
Write a program using functions to check whether a number is even or odd.
AIM:
To check whether a number is even or odd using user defined function
CODING:
def oddeven(a):
if(a%2==0):
return “Even”
else:
return “Odd”
num = int(input("Enter a number:"))
print("The given number is”, oddeven(num))

OUTPUT:
Enter a number: 7
The given number is Odd
Enter a number: 6
The given number is Even

RESULT:

Thus the Python program to check whether a number is odd or even has been done and the
output is verified.

91
PY 2(b) - REVERSE THE STRING
QUESTION:
Write a program to create reverse of the given string. For example, “wel” = “lew“. (Don’t
use string slice with stride operation)
AIM:
To create a reverse of the given string
CODING:
def rev(str1):
str2=''
for i in str1:
str2 = i+str2
return str2
word=input("\n Enter a string:")
print("\n The reverse of the string is:", reverse(word))

OUTPUT:
Enter a string: school
The reverse of the given string is: loohcs

RESULT:

Thus the Python program to reverse the string has been done and the output is verified.

92
PY 3. GENERATE VALUES AND REMOVE ODD NUMBERS
QUESTION:
Write a program to generate values from 1 to 10 and then remove all the odd numbers from
the list.
AIM:
To generate values from 1 to 10 and then remove all the odd numbers from the list.
CODING:
num= list(range(1,11))
print("Numbers from 1 to 10... \n", num)
for i in num:
if(i%2==1):
num.remove(i)
print("The value after removing odd numbers. ... \n", num)

OUTPUT:
Numbers from 1 to 10...
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The value after removing odd numbers....
[2, 4, 6, 8, 10]

RESULT:

Thus the Python program to generate values from 1 to 10 and then remove all the odd
numbers from the list has been done and the output is verified.

93
PY 4 - GENERATE PRIME NUMBERS AND SET OPERATIONS
QUESTION:
Write a Program that generates a set of prime numbers and another set of odd numbers.
Display the result of union, intersection, difference and symmetric difference operations.
AIM:
To generate a set of prime numbers and another set of odd numbers, and to display the
result of union, intersection, difference and symmetric difference operations.
CODING:
odd=set(range (1,10,2))
prime=set()
for i in range(2,10):
for j in range (2,i):
if (i%j==0):
break
else:
prime.add(i)
print("Odd number:", odd)
print("Prime number:", prime)
print("Union:", odd.union(prime))
print("Intersection:", odd.intersection(prime))
print("Difference:", odd.difference(prime))
print("Symmetric Difference:", odd.symmetric_difference(prime))
OUTPUT:
Odd number: {1, 3, 5, 7, 9}
Prime number: {2, 3, 5, 7}
Union: {1, 2, 3, 5, 7, 9}
Intersection: {3, 5, 7}
Difference: {1, 9}
Symmetric Difference: {1, 2, 9}

RESULT:

Thus the Python program to generate prime numbers and set operations has been done and
the output is verified.

94
PY 5 - DISPLAY A STRING ELEMENTS – USING CLASS
QUESTION:
Write a program to accept a string and print the number of uppercase, lowercase, vowels,
consonants and spaces in the given string using Class.
AIM:
To accept a string and print the number of uppercase, lowercase, vowels, consonants and
spaces in the given string using Class.
CODING:
class string:
def init (self):
self.upper=0
self.lower=0
self.vowel=0
self.consonant=0
self.space=0
self.string=""
def getstr(self):
self.string=str(input("Enter a string:"))
def count(self):
for ch in self.string:
if(ch.isupper()):
self.upper+=1
if(ch.islower()):
self.lower+=1
if(ch in('AEIOUaeiou')):
self.vowel+=1
if(ch==" "):
self.space+=1
self.consonant=self.upper+self.lower-self.vowel
def display(self):
print("The given string contains. ... ")
print("%d Uppercase letters"%self.upper)
95
print("%d Lowercase letters"%self.lower)
print("%d Vowels"%self.vowel)
print("%d Consonants"%self.consonant)
print("%d Spaces"%self.space)
s=string()
s.getstr()
s.count()
s.display()

OUTPUT:
Enter the string: Welcome to Computer Science
The given sting contains.....
3 uppercase letters
21 lowercase letters
10 vowels
14 consonants
3 spaces

RESULT:

Thus the Python program to display a string elements – using class has been done and the
output is verified.

96
DB 6 - MYSQL – EMPLOYEE TABLE
QUESTION:
Create an Employee Table with the fields Empno, Empname, Desig, Dept, Age and Place. Enter
five records into the table.
 Add two more records to the table.
 Modify the table structure by adding one more field namely date of joining.
 Check for Null value in doj of any record.
 List the employees who joined after 01/01/2018.
AIM:
(1) To Create employee table with Empno, Empname, Desig, Dept, Age and Place fields.
(2) Insert five records
(3) Add two more records
(4) Modify table structure
(5) Check for NULL values
(6) List required subset of records
SQL QUERIES AND OUTPUT:
(i) Creating Database:
mysql> create database company;
Query ok, 1row affected (0.00 sec)
mysql> use company;
Database Changed
(ii) Creating Table Employee:
mysql> create table employee (Empno integer(4) primary key, Empname varchar(20),
Desig varchar(10), Dept varchar(10), Age integer(2), Place varchar(10));
(iii) View Table Structure:
mysql> desc employee;

(iv) Inserting Data into Table:


mysql> insert into employee values(1221, 'Sidharth', 'Officer', 'Accounts', 45, 'Salem');
mysql> insert into employee values(1222, 'Naveen', 'Manager', 'Admin', 32, 'Erode');
mysql> insert into employee values(1223, 'Ramesh', 'Clerk', 'Accounts', 33, 'Ambathur');
mysql> insert into employee values(1224, 'Abinaya', 'Manager', 'Admin', 28, 'Anna Nagar');
mysql> insert into employee values(1225, 'Rahul', 'Officer', 'Accounts', 31, 'Anna Nagar');

97
(v) Select all the record:
mysql> select * from employee;

(vi) Adding two more records:


mysql> insert into employee values(3226, 'Sona', 'Manager', 'Accounts', 42, 'Erode');
mysql> insert into employee values(3227, 'Rekha', 'Officer', 'Admin', 34, 'Salem');
(vii) Select all the record:
mysql> select * from employee;

(viii) Adding one more Field:


mysql> alter table employee add(doj date);
(ix) View Table Structure:
mysql> desc employee;

(x) Inserting date of joining to each employee:


mysql> update employee set doj = '2010-03-21' where empno=1221;
mysql> update employee set doj = '2012-05-13' where empno=1222;
mysql> update employee set doj = '2017-10-25' where empno=1223;
mysql> update employee set doj = '2018-06-17' where empno=1224;
mysql> update employee set doj = '2018-01-02' where empno=1225;
mysql> update employee set doj = '2017-12-31' where empno=3226;
mysql> update employee set doj = '2015-08-16' where empno=3227;

98
(xi) Select all the record:
mysql> select * from employee;

(xii) Checking null value in doj


mysql> select * from employee where empno is null;
Empty set (0.00 sec)
(xiii) List the employees who joined after 01/01/2018.
mysql> Select * from employee where doj > '2018-01-01';

RESULT:
Thus the MySQL employee table has been done and the output is verified.
DB 7 - MYSQL – STUDENT TABLE
QUESTION:
Create a table with following fields and enter data as given in the table below.

Data to be entered

Then, query the followings:


(i) List the students whose department is “Computer Science”.
(ii) List all the students of age 20 and more in Mechanical department.
(iii) List the students department wise.
(iv) Modify the class M2 to M1.
(v) Check for the uniqueness of Register no.

AIM:
(1) Create student table and inserting records
(2) List the students whose department is “Computer Science”.
(3) List all the students of age 20 and more in Mechanical department.
(4) List the students department wise.
(5) Modify the class M2 to M1.
(6) Check for the uniqueness of Register no.

SQL QUERIES AND OUTPUT:


(i) Creating Database:
mysql> create database school;
Query ok, 1row affected (0.00 sec)
mysql> use school;
Database Changed
(ii) Creating Table - Student :
mysql> create table student (Reg_No char(5), Sname varchar(20), Age integer(2), Dept
varchar(10), Class char(3));
Query OK, 0 rows affected (0.51 sec)
(iii) View Table Structure:
mysql> desc student;

(iv) Inserting Data into table:


mysql> insert into student values ('M1001', 'Harish', 19, 'ME', 'ME1');
mysql> insert into student values ('M1002', 'Akash', 20, 'ME', 'ME2');
mysql> insert into student values ('C1001', 'Sneha', 20, 'CSE', 'CS1');
mysql> insert into student values ('C1002', 'Lithya', 19, 'CSE', 'CS2');
mysql> insert into student values ('E1001', 'Ravi', 20, 'ECE', 'EC1');
mysql> insert into student values ('E1002', 'Leena', 21, 'EEE', 'EE1');
mysql> insert into student values ('E1003', 'Rose', 20, 'ECE', 'EC2');

(v) View all the Records:


mysql> select * from student;

(vi) List the students whose department is “CSE”:


mysql> select * from student where Dept='CSE';

(vii) List all the students of age 20 and more in ME department:


mysql> select * from student where Age >=20 and Dept='ME';
(viii) List the students department wise:
mysql> select * from student Group by Dept Order by Sname;

(ix) Modify the class M2 to M1:


mysql> update student set Class='ME1' where Class='ME2';
Query OK, 1 row affected (0.11 sec)
Rows matched: 1 Changed: 1 Warnings: 0

(x) View all the Records:


mysql> select * from student;

(xi) Check for the uniqueness of Register no.


mysql> select distinct Reg_No from student;

RESULT:
Thus the MySQL student table has been done and the output is verified.
PY 8 - PYTHON WITH CSV
QUESTION:
Write a program using python to get 10 players name and their score. Write the input in a csv
file. Accept a player name using python. Read the csv file to display the name and the score. If the
player name is not found give an appropriate message.
AIM:
To get 10 players name and their score. Write the input in a csv file. Accept a player name
using python. Read the csv file to display the name and the score. If the player name is not found
give an appropriate message.
CODING:
import csv
with open('c:\\pyprg\\player.csv','w',newline='') as f:
w = csv.writer(f)
n=1
while (n<=10):
name = input("Player Name?:" )
score = int(input("Score: "))
w.writerow([name,score])
n+=1
print("Player File created")
f.close()
searchname=input("Enter the name to be searched: ")
f=open('c:\\pyprg\\player.csv','r')
reader =csv.reader(f)
lst=[]
for row in reader:
lst.append(row)
q=0
for row in lst:
if searchname in row:
print(row)
q+=1
if(q==0):
print("string not found")
f.close()
OUTPUT:
Player Name: Rohit Sharma
Score: 264
Player Name: Virender Sehwag
Score: 219
Player Name: Sachin Tendulkar
Score: 200
Player Name: Dhoni
Score: 190
Player Name: Sachin Tendulkar
Score: 250
Player Name: Virat Kohli
Score: 148
Player Name: Yuvaraj singh
Score: 158
Player Name: KapilDev
Score: 175
Player Name: Amarnath
Score: 148
Player Name: Sunil Gavaskar
Score: 200
Player File created
Enter the name to be searched: Sachin Tendulkar
[' Sachin Tendulkar ', '200']
[' Sachin Tendulkar ', '250']

RESULT:

Thus the Python with CSV has been done and the output is verified.
PY 9 - PYTHON WITH SQL
QUESTION:
Create a sql table using python and accept 10 names and age .sort in descending order of
age and display.
AIM:
To create a sql table using python and accept 10 names and age. sort in descending order of
age and display.
CODING:
import sqlite3
connection = sqlite3.connect("info.db")
cursor = connection.cursor()
cursor.execute("create table student(name, age)")
print("Enter 10 Students names and their ages respectively:")
for i in range(10):
who =[input("Enter Name:")]
age =[int(input("Enter Age:"))]
n =len(who)
for i in range(n):
cursor.execute("insert into student values (?, ?)", (who[i],age[i]))
cursor.execute("select * from student order by age desc")
print("Displaying All the Records From student Table in Descending order of age")
print (*cursor.fetchall(),sep='\n' )
OUTPUT:
Enter 10 Students Names and their Ages Respectively:
Enter Name: Annamalai
Enter Age:17
Enter Name: Aashik Mathew
Enter Age:23
Enter Name: Kumaran
Enter Age:30
Enter Name: Sivasakthiya
Enter Age:28
Enter Name: Leena
Enter Age:45
Enter Name: Meena
Enter Age:65
Enter Name: Kamalakannan
Enter Age:35
Enter Name: Sowmyaa
Enter Age:20
Enter Name: Ramaa
Enter Age: 70
Enter Name: Melvin
Enter Age:35
Displaying All the Records From student Table in Descending order of age
('Ramaa', 70)
('Meena', 65)
('Leena', 45)
('Kamalakannan', 35)
('Melvin', 35)
('Kumaran', 30)
('Sivasakthiya', 28)
('Aashik Mathew', 23)
('Sowmyaa ', 20)
('Annamalai', 17)

RESULT:

Thus the Python with SQL has been done and the output is verified.
PY 10 - PYTHON GRAPHICS WITH PIP
QUESTION:
Write a program to get five marks using list and display the marks in pie chart.
AIM:
To get five marks using list and display the marks in pie chart using matplot.
CODING:
import matplotlib.pyplot as plt
marks=[]
i=0
subjects = ["Tamil", "English", "Maths", "Science", "Social"]
while i<5:
marks.append(int(input("Enter Mark = ")))
i+=1
for j in range(len(marks)):
print("{}.{} Mark = {}".format(j+1, subjects[j],marks[j]))
plt.pie (marks, labels = subjects, autopct = "%.2f ")
plt.show()

OUTPUT:
Enter Mark = 67
Enter Mark = 31
Enter Mark = 45
Enter Mark = 89
Enter Mark = 73
1. Tamil Mark = 67
2. English Mark = 31
3. Maths Mark = 45
4. Science Mark = 89
5. Social Mark = 73

RESULT:
Thus the Python graphics with pip has been done and the output is verified.

You might also like