0% found this document useful (0 votes)
133 views

XII Computer Science EM Five Mark Question and Answer

The document discusses different types of functions like pure functions and impure functions, with examples explaining that pure functions always return the same output for the same input, while impure functions may modify arguments or have non-deterministic behavior. It also covers topics like data abstraction using constructors and selectors to define abstract data types, lists as a way to bundle multiple values, and different scopes of variables like local, global, and enclosed scope.

Uploaded by

rsgk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views

XII Computer Science EM Five Mark Question and Answer

The document discusses different types of functions like pure functions and impure functions, with examples explaining that pure functions always return the same output for the same input, while impure functions may modify arguments or have non-deterministic behavior. It also covers topics like data abstraction using constructors and selectors to define abstract data types, lists as a way to bundle multiple values, and different scopes of variables like local, global, and enclosed scope.

Uploaded by

rsgk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

N.S.Hr.Sec.

School, Theni * They do not modify the arguments which are passed
to them.
XII – Computer Science (5M Questions)
let square x:=
Lesson 1 - Function
return: x * x
1) What are called Parameters and write a note on
* The above function square is a pure function
(i) Parameter without Type (ii) Parameter with Type because it will not give different results for same
Parameters are the variables in a function definition input.
and arguments are the values which are passed to a Impure functions
function definition.
* The return value of the impure functions does not
Parameter without Type solely depend on its arguments passed.
Let us see an example of a function definition:
* They may modify the arguments which are passed to
let bigger a b := them.
let randomnumber :=
if a > b then return a
a := random()
else return b
return a
* Variables a and b are parameters. * The above function is an impure function because
* We have not mentioned any data types. the randon()will give different outputs for the same
* Some language compilers solve this type inference function call.
algorithmically. 4. Explain with an example interface and
Parameter with Type implementation.
Now let us write the same function definition with Interface
types. * Interface just defines what an object can do, but
let bigger (a:int) (b:int) :int := won’t actually do it.
if a > b then return a * In object oriented programs classes are the interface
and how the object is processed and executed is the
else return b implementation.
* Here we have mentioned the data types. * For example when you press a light switch, the light
* Parentheses are mandatory to mention the data goes on, you may not have cared how it splashed
type for a and b. the light.
* This is useful on times when you get a type error * A light, should have function definitions like
from the compiler. turn_on () and a turn_off ().
2. Identify in the following program Implementation
let rec gcd a b := * Implementation carries out the instructions defined
in the interface.
if b <> 0 then gcd b (a mod b) else return a
* For example, the person who drives the car doesn't
i) Name of the function – gcd
care about the internal working.
ii) Identify the statement which tells it is a recursive
Internally, the engine of the car is doing all the things.
function – rec keyword
* It's where fuel, air, pressure, and electricity come
iii) Name of the argument variable – a and b
together to create the power to move the vehicle.
iv) Statement which invoke the function recursively –
* Thus we separate interface from implementation.
gcd b (a mod b)
v)Statement which terminates the recursion – return a
3. Explain with example Pure and impure functions.
Pure functions
* Pure functions are functions which will give exact
result when the same arguments are passed.
* The return value of the pure functions solely
depends on its arguments passed.

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 1


Lesson 2 - Data Abstraction class Person:
1. How will you facilitate data abstraction. Explain it creation( )
with suitable example. firstName := " "
Data abstraction is used to define an Abstract Data lastName := " "
Type (ADT), which is a collection of constructors and id := " "
selectors.
email := " "
Constructors are functions that build the abstract data
The new data type Person is pictorially represented as
type.
city:= makecity (name, lat, lon) Person class name (multi part data representation)
Here makecity (name, lat, lon) is the constructor firstName
which creates the object city. lastName
Selectors are nothing but the functions that retrieve id variables belong to the new data type
information from the data type. email
• getname(city) creation ( ) function belongs to the new data type
• getlat(city)
• getlon(city) let main() contains
are the selectors, because these functions extract the p1:=Person()
information of the city object. firstName := "Rajesh "
2. What is a List? Why List can be called as Pairs. lastName :="Kanna"
Explain with suitable example.
id :="1234"
List is constructed by placing expressions within
square brackets separated by commas. email:="[email protected]"
Each value can be of any type and can even be In this example Person is referred to as a class or a
another list. type, while p1 is referred to as an object or an
instance.
Example for list is lst := [10, 20]
Lesson 3 – Scoping
The elements of a list can be accessed in two ways.
I. Multiple assignment 1 Explain the types of scopes for variable or LEGB rule
with example.
lst := [10, 20]
Scope refers to the accessibility of a variable with in
x, y := lst
one part of a program to another part of the same
In the above example x will become10 and y will program. There are 4 types of Variable Scope.
become 20.
Local Scope
II. Element selection operator
Local scope refers to variables defined in current
lst[0] is 10 and lst[1] is 20 function. Example :-
Any way of bundling two values together into one can Disp():
be considered as a pair.
a:=7
Mathematically we can represent list similar to a set.
print a
lst[(0, 10), (1, 20)] – where
Disp() Output is 7
Global Scope
A variable which is declared outside of all the
functions in a program is known as global variable.
Therefore List can be called as Pairs.
Example:-
3. How will you access the multi-item. Explain with
a:=10
example.
Disp():
The structure construct or class construct is used to a:=7
represent multi-part objects where each part is print a 7
named. Disp()
Consider the following pseudo code: print a  10

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 2


Enclosed Scope Lesson 4 - Algorithmic strategies
A variable which is declared inside a function which 1. Explain the characteristics of an algorithm.
contains another function definition with in it. Input – Zero or more quantities to be supplied.
Example:- Output – At least one quantity is produced.
Disp(): Finiteness – Algorithms must terminate after finite
a:=10 number of steps.
Disp1():
Effectiveness – Every instruction must be carried out
print a 10
effectively.
Disp1()
print a 10 Correctness – The algorithms should be error free.
Disp() Simplicity – Easy to implement.
Built-in Scope Unambiguous – Algorithm should be clear and
Any variable or function which is defined in the unambiguous.
modules of a programming language has Built-in or Independent – An algorithm should be independent of
module scope. any programming code.
Example:- 2. Discuss about Linear search algorithm.
Built-in or module scope Linear search is also called sequential search.
Disp(): This method checks the search element with each
a:=10 element in sequence until the desired element is
print a found.
Disp() In this searching algorithm, list need not be ordered.
2. Write any Five Characteristics of Modules. Pseudo code
1. Modules contain instructions, logic, and data. * Let us assume that, x be the search element,
2. Modules can be separately compiled and stored in a * Start from the first element of the array and one by
library. one compare x with each element of the array.
3. Modules can be included in a program. * If x matches with an element, return the index.
4. Module segments can be used by invoking a name * If x doesn’t match with any of the elements,
and some parameters. return -1.
5. Module segments can be used by other modules Example:
3. Write any five benefits in using modular To search the number 20 in the array given below,
programming linear search will go step bystep in a sequential order
• Less code to be written. starting from the first element.
• 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.
1) Search Element : 20
• The scoping of variables can easily be controlled
Item found at : 6
2) Search Element : 35
Item found at : -1 (not found)

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 3


3. What is Binary search? Discuss with example.
Binary search also called half-interval search
algorithm.
It finds the position of a search element within a
sorted array.
This searching technique follows the divide and
conquer approach.
Pseudo code for Binary search
• Start with the middle element.
• If the key is found at middle element, then return
in index of middle element.
• If the key is smaller than the middle element, 5. Explain the concept of Dynamic programming with
then the left side is used for next search. suitable example.
• If the key is larger than the middle element, then Dynamic programming is a technique that breaks the
the right side is used for next search. problems into sub-problems, and saves the result for
• This process is continued until the key is found or future purposes so that we do not need to compute
no elements to search. the result again.
Example: Steps to do Dynamic programming
• It breaks down the complex problem into simpler
sub-problems.
• It finds the optimal solution to these sub-
problems.
• It stores the results of sub-problems
(memoization).
• Finally, calculate the result of the complex
problem.
Dynamic programming approach for Fibonacci series:
4. Explain the Bubble sort algorithm with example. Initialize f0=0, f1 =1
Bubble sort, also known as comparison sort, is the step-1: Print the initial values of Fibonacci f0 and f1
easiest sorting algorithm.
step-2: Calculate Fibonacci fib ← f0 + f1
It compares each pair of adjacent elements and swaps
step-3: Assign f0← f1, f1← fib
them if they are in the unsorted order.
step-4: Print the next consecutive value of Fibonacci
Although the algorithm is simple, it is too slow and
fib
less efficient when compared to other sorting
methods. step-5: Go to step-2 and repeat until the specified
number of terms generated
Procedure
For example if we generate Fibonacci series up to 10
1) Start with the first element.
digits, the algorithm will generate the series as shown
2) Compare the current element with the next below:
element.
The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55
3) If the current element is greater than the next
element, then swap both the elements. If not, move
to the next element.
4) Repeat steps 1 – 3 until we get the sorted list.
Example:

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 4


5. PYTHON – VARIABLES AND OPERATORS 1) Keywords,
1. Describe in detail the procedure of Script mode 2) Identifiers,
programming. 3) Operators,
Basically, a script is a text file containing the Python 4) Delimiters and
statements. It can be executed again and again
5) Literals.
without retyping.
1. Keywords: Keywords are words that have some
1. Choose File → New File or press Ctrl + N in Python
special meaning. They can’t be used for any other
shell window.
purpose.
2. An untitled blank script text editor will be displayed
Ex: False, True, class, break, continue, while, for,
on screen.
import etc.
3. Type the following code in Script editor
2. Identifiers: An Identifier is a name used to identify a
a =100 variable, function, class, module or object. Python is a
b = 350 case-sensitive language.
c = a+b Example of valid identifiers
print ("The Sum=", c) sum, total_marks, regno, num1
4. Choose File → Save or Press Ctrl + S 3. Operators: In computer programming languages
In the Save As dialog box, type the file name in File operators are special symbols which represent
Name box computations, conditional matching etc.
5. Choose Run → Run Module or Press F5 to execute Operators are categorized as Arithmetic, Relational,
the code. Logical, Assignment etc.
6. For all error free code, the output will appear in the Value and variables when used with operator are
IDLE window. known as operands.
2. Explain input() and print() functions with examples. 4. Delimiters (Punctuators): These are the symbols
that used in Python to organize the structures,
The print() function
statements, and expressions.
In Python, the print() function is used to display result
Some of the delimiters are: [ ] { } ( ) = : , etc.
on the screen. The syntax for print() is as follows:
5. Literals: Literal is a raw data given to a variable or
print(message)
constant.
print(message, variable)
In Python, there are various types of literals.
Example:
1) Numeric 2) String 3) Boolean
print(“Hello Python”)
(i) Numeric Literals consist of digits and are immutable
a=5 (unchangeable).
print(“a= “, a) Ex: rollno=101
The input() function pi=3.14
In Python, input( ) function is used to accept data as (ii) In Python a string literal is a sequence of characters
input at run time. The syntax for input() function is, surrounded by quotes.
variable = input (“prompt string”) Ex: name=”Rajesh”
Where, prompt string is a message to the user. (iii) A Boolean literal can have any of the two values:
Example: True or False.
name = input("Enter your name: ") Ex: choice=True
print(name)
3. Discuss in detail about Tokens in Python Prepared by
Tokens
S.Ganesh Kumar , B.Sc.,B.Ed.,M.S.I.T.
A token is the smallest individual unit in a python
program. All statements and instructions in a program N.S.Hr.Sec.School, Theni
are built with tokens.
The normal token types are

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 5


CHAPTER 6 CONTROL STRUCTURES 4. Write a program to display multiplication table for a
1. Write a detailed note on for loop. given number.
The for loop is usually known as a definite loop. n=int(input("Enter table number "))
Because the programmer knows exactly how many for i in range(1,11):
times the loop will be executed. print(" %d x %d = %d " %( i , n , i*n ))
Syntax:
for variable in sequence : CHAPTER 7 PYTHON FUNCTIONS
statements 1. Explain the different types of function with an
Here the sequence is the collection of ordered or example.
unordered values or even a string. Functions are nothing but a group of related
The control variable accesses each item of the statements that perform a specific task.
sequence on each iteration until it reaches the last Function types:
item. Built-in Functions
Example: Output User-defined Functions
P
for x in “Python” : y Lambda Functions
print(x) t Recursive Functions
h Built-in Functions:
o
Functions that are inbuilt with in Python.
n
Ex: max( ) – Returns the maximum value in a list.
2. Write a detailed note on if..elif..else statement with User-defined functions
suitable example. Functions defined by the users themselves.
The elif statement enables us to check multiple Function blocks begin with the keyword “def ”
conditions and execute the specific block of
Ex: def hello( ):
statements.
print (“hello - Python”)
Syntax:
return
if condition1:
Lambda functions
code block 1
Lambda Functions are anonymous functions.
elif condition2:
We can use the lambda keyword to define an
code block 2
un-named function.
else:
lambda arguments: expression
code block 3
Ex: x = lambda a : a + 10
Multiple if..else statements can be combined to one print(x(5))
if..elif…else. ‘ elif ’ can be considered to be
Recursive Functions
abbreviation of ‘ else if ’.
When a function calls itself is known as recursion.
Example:
A base condition is must in every recursive function
number = int(input(“Enter a number”))
otherwise it will continue to execute like an infinite
if number == 0: loop.
print("Zero") Ex:
elif number > 0: def fact(n) :
print(“Positive number”) if n == 1:
else: return 1
print('Negative number') else:
return n * fact (n-1)
3. Write a program to display all 3 digit odd numbers.
for i in range(101 , 1000 , 2):
print(i , end = " ")

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 6


2. Explain the scope of variables with an example. (d) type( )
Scope of variable refers to the part of the program, Returns the type of data stored in the objects or
where it is accessible. variables.
There are two types of scopes - Ex: x= 15.2
local scope and global scope. print (type (x))
Local Scope Output: <class ‘float’>
A variable declared inside a function belongs to local (e) pow ()
scope.
This function is used to compute the powers of a
A variable with local scope can be accessed only number. It returns x to the power of y.
within the function.
Ex: x=5
Example
y=2
def myfunc():
Print(pow(x,y))
x = 300 local scope
Output: 25
print(x)
4. Write a Python code to find the L.C.M. of two
myfunc() numbers.
Global scope num1 = int(input(" Enter First number : "))
In Python, a variable declared outside of the function num2 = int(input(" Please Second number : "))
is known as a global variable. a = num1
This means that a global variable can be accessed b = num2
inside or outside of the function.
while(num2 != 0):
Example
temp = num2
x = 300 global scope num2 = num1 % num2
def myfunc( ) : num1 = temp
print(x)
gcd = num1
myfunc( ) lcm = (a * b) / gcd

3. Explain the following built-in functions. (a) id() (b) print("\n GCD = ",gcd)
chr() (c) round() (d) type() (e) pow() print("\n LCM = ",lcm)
(a) id( ) 5. Explain recursive function with an example.
Returns the “identity” or the address of the object in When a function calls itself is known as recursion.
memory. A base condition is must in every recursive function
Ex: x=15 otherwise it will continue to execute like an infinite
print (“address of x is :” , id (x) ) loop.
Output: address of x is : 1357486752 Ex:
(b) chr( ) def fact(n) :
Returns the Unicode character for the given ASCII if n == 1:
value. return 1
else:
Ex: c = 65
return n * fact (n-1)
print (chr (c) )
Output: A print(fact(6))
(c) round( ) The recursion ends when the number reduces to 1.
round() function that rounds off a number to the given This is called the base condition.
number of digits.
Ex: average=76.32
Print(round(average,1))
Output: 76.3

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 7


CHAPTER 8 STRINGS AND STRING MANIPULATION CHAPTER 9 LISTS, TUPLES, SETS AND DICTIONARY
1. Explain about string operators in python with 1. What the different ways to insert an element in a
suitable example. list. Explain with suitable example.
Python provides the following operators for string There are three methods to add elements to a List in
operations. These operators are useful to manipulate Python.
string. Append( )
(i) Concatenation (+) The append() method is used to add an element to the
Joining of two or more strings is called as end of the list.
Concatenation. my_list = [1, 2, 3]
The plus (+) operator is used to concatenate strings in my_list.append(4)
python.
print(my_list)
Example
Output: [1, 2, 3, 4]
str1= "welcome" + "Python"
extend( )
print(str1)
extend() function is used to add more than one
Output: 'welcomePython' element to an existing list.
(ii) Append (+ =) my_list = [1, 2, 3]
Adding more strings at the end of an existing string is my_list.extend( [4 , 5] )
known as append.
print(my_list)
The operator += is used to append a new string with
Output: [1, 2, 3, 4, 5]
an existing string.
insert( )
Example
The insert() function is used to insert an element at
str1="Hello "
any position of a list.
str1 += " Python"
my_list = ["apple", "banana", "cherry"]
print (str1)
my_list.insert(1,"mango")
Output: Hello Python
print(my_list)
(iii) Repeating (*)
Output: ['apple', 'mango', 'banana', 'cherry']
The multiplication operator (*) is used to display a
2. What is the purpose of range()? Explain with an
string in multiple number of times.
example.
Example
The range() function is used to generate a series of
str1="Welcome " values in Python.
print (str1*4) The range() function has three arguments.
Output: Welcome Welcome Welcome Welcom range (start , stop, step)
(iv) String slicing where,
Slice is a substring of a main string. A substring can be start - Optional. Start value of the series. Default is 0
taken from the original string by using [ ] operator.
stop - Required. End value of the series (not included)
General format of slice operation: str[start:end]
step - Optional. Increment value of the series.
Example Default is 1
>>> str1="THIRUKKURAL" Example : Generating first 10 even numbers
>>> print (str1[0]) for x in range (2, 11, 2):
T print(x)
Output
2
4
6
8
10

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 8


3. What is nested tuple? Explain with an example. print(A – B) or print(A.difference(B))
In Python, a tuple can be defined inside another tuple; output: {1, 2}
called Nested tuple. (iv) Symmetric difference
In a nested tuple, each tuple is considered as an The symmetric difference between two sets includes
element. all elements without the common elements.
The for loop will be useful to access all the elements in In Python, we use the caret ^ operator or the
a nested tuple. symmetric_difference() method to perform symmetric
Example difference between two sets.
Toppers = (("Raja", "XII-F", 98.7), ("Mani", "XII-H", 97.5), Ex: A={1,2,3,4}
("Tharani", "XII-F", 95.3), ("Saisri", "XII-G", 93.8)) B={3,4,5,6}
for i in Toppers: print(A^B) or print(A.symmetric_difference(B))
print(i) output: {1, 2, 5, 6}
Output:
('Raja', 'XII-F', 98.7)
CHAPTER 10 PYTHON CLASSES AND OBJECTS
('Mani', 'XII-H', 97.5)
1. Explain about constructor and destructor with
('Tharani', 'XII-F', 95.3) suitable example.
('Saisri', 'XII-G', 93.8) Constructor
A constructor is a special type of function which is
4. Explain the different set operations supported by used to initialize the members of the class.
python with suitable example. In Python the __init__() method is called the
As you learnt in mathematics, the python is also constructor and is always called when an object is
supports the set operations such as Union, created.
Intersection, difference and Symmetric difference. Destructor
(i) Union: Destructor is also a special method to destroy the
It includes all elements from two or more sets. objects.
In python, the operator | and the function union() are In Python, __del__( ) method is used as destructor. It
used to join two sets in python. is just opposite to constructor.
A={1,2,3,4} Example
B={3,4,5,6} class sample( ) :
print(A|B) or print(A.union(B)) def __init__(self) :
output: {1, 2, 3, 4, 5, 6} print("it a constructor")
(ii) Intersection: def __del__(self) :
It includes the common elements in two sets. print("it a destructor")
In python, the operator & and the function obj = sample()
intersection() are used to intersect sets in python.
Ex: A={1,2,3,4} CHAPTER 11 DATABASE CONCEPTS
B={3,4,5,6} 1. Explain the different types of data model.
print(A&B) or print(A.intersection(B)) A data model describes how the data can be stored
output: {3, 4} and accessed from a software after complete
(iii) Difference implementation.
It includes all elements that are in first set but not in Hierarchical Model
the second set. Hierarchical model was developed by IBM as
The minus (-) operator and the function difference() Information Management System.
are used to do difference operation. In Hierarchical model, data is represented as a simple
Ex: A={1,2,3,4} tree like structure form.
B={3,4,5,6}

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 9


This model represents a one-to-many relationship i.e
parent-child relationship.
Network Model
Network database model is an extended form of
hierarchical data model. The difference between
hierarchical and Network data model is :
• In hierarchical model, a child record has only one
parent node.
• In a Network model, a child may have many parent One-to-Many Relationship
nodes. It represents the data in manyto-many One row in a table A is linked to many rows in a table
relationships. B, but one row in a table B is linked to only one row in
• This model is easier and faster to access the data. table A.
Relational Model
This model was introduced by E.F Codd in 1970.
The basic structure of data in the relational model
is tables.
The relationship is maintained by storing a common
field.
Hence, tables are also known as relations.
Entity Relationship Model. (ER model)
It was developed by Chen in 1976. Many-to-One Relationship
Relationship are created by dividing the object into In Many-to-One Relationship, many entities can be
entity and characteristics into attributes. related with only one in the other entity.
It is very simple and easy to design logical view of
data.
The developer can easily understand the system by
looking at ER model.
Object model
Object model stores the data in the form of objects,
attributes and methods.
This model handles more complex applications, such
as Geographic information System.
Many-to-Many Relationship
It is used in file Management System.
A many-to-many relationship occurs when multiple
It represents real world objects, attributes and records in a table are associated with multiple records
behaviors. in another table.
2. Explain the different types of relationship mapping.
One-to-One Relationship
In One-to-One Relationship, one entity is related with
only one other entity.
For example: A student can have only one exam
number.

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 10


3. Differentiate DBMS and RDBMS. SET DIFFERENCE ( Symbol – )
Basis of The result of A – B, is a relation which includes all
DBMS RDBMS tuples that are in A but not in B.
Comparison
Relational Example:
Database
Database ∏ RollNo (STUDENT) – ∏ RollNo (MARKS)
Expansion Management
Management
System PRODUCT OR CARTESIAN PRODUCT (Symbol : X )
System
Relational model Cross product is a way of combining two relations. The
Data storage Navigational model
(in tables). resulting relation contains, both relations being
Data combined.
Present Not Present
redundancy Example:
RDBMS uses
Normalization Not performed normalization to (STUDENT) X (MARKS)
reduce redundancy 5. Explain the characteristics of RDBMS.
Consumes more Faster, compared
Data access
time to DBMS. RDBMS
Transaction Inefficient and Efficient and
management insecure. secure
Expansion Relational Database Management System
Distributed Supported by
Not supported
Databases RDBMS. Data storage Relational model (in tables).
Oracle, MySql, Data
Example Dbase, FoxPro. Not Present
SQLite redundancy
RDBMS uses normalization to reduce
Normalization
4. Explain the different operators in Relational algebra redundancy
with suitable examples. Data access Faster, compared to DBMS.
Relational Algebra is a procedural query language Transaction
Efficient and secure
used to query the database tables using SQL. management
SELECT (symbol : σ) Distributed
Supported by RDBMS.
The select operation selects tuples that satisfy a given Databases
condition. Example Oracle, MySql, SQLite
Example:
σ course = “Big Data” (STUDENT) CHAPTER 12 - STRUCTURED QUERY LANGUAGE (SQL)
PROJECT (symbol : Π) 1. Write the different types of constraints and their
functions.
This operation shows the list of attributes that we
wish to appear in the result. SQL Constraints
Rest of the attributes are eliminated from the table. Constraint is a condition applicable on a field or set of
fields.
Example:
Column constraint: Column constraint apply only to
∏ RollNo, Name (STUDENT)
individual column.
UNION (Symbol :∪)
Table constraint : Table constraint apply to a group of
It includes all tuples that are in tables A or in B. one or more columns.
It also eliminates duplicates. Type of Constraints:
Example: NOT NULL - Ensures that a column cannot have a NULL
∏ RollNo, Name (STUDENT) U ∏ Rank (MARKS) value
INTERSECTION (symbol : ∩) UNIQUE - Ensures that all values in a column are
Defines a relation consisting of a set of all tuple that different
are in both in A and B. PRIMARY KEY - A combination of a NOT
Example: NULL and UNIQUE. Uniquely identifies each row in a
table
∏ RollNo, Name (STUDENT) ∩ ∏ RollNo (MARKS)

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 11


CHECK - Ensures that the values in a column satisfies a INSERT - Inserts data into a table.
specific condition UPDATE - Updates the existing data within a table.
DEFAULT - Sets a default value for a column if no value DELETE - Deletes all records from a table, but not the
is specified space occupied by them.
Example: DCL - Data Control Language
CREATE TABLE Student ( Adno integer PRIMARY KEY DCL is a language used to control the access of data
Name char(20) NOT NULL, stored in a database.
Age integer CHECK (Age <=19), GRANT - It is used to give user access privileges to a
Place char(10) DEFAULT "Theni" database.
); REVOKE - It is used to take back permissions from the
user.
2. Consider the following employee table. Write SQL
commands for the questions.(i) to (v). TCL - Transaction Control Language
EMPCODE NAME DESIG PAY ALLOWANCE TCL commands are used to manage transactions in the
S1001 Hariharan Supervisor 29000 12000 database.
P1002 Shaji Operator 10000 5500 COMMIT - Saves any transaction into the database
P1003 Prasad Operator 12000 6500 permanently.
C1004 Manjima Clerk 8000 4500 ROLL BACK - Restores the database to last commit
M1005 Ratheesh Mechanic 20000 7000 state.
(i) To display the details of all employees in DQL - Data Query Language
descending order of pay. It consist of commands used to query or retrieve data
SELECT *FROM employee ORDER BY PAY DESC; from a database.
(ii) To display all employees whose allowance is SELECT - Displays the records from the table.
between 5000 and 7000. 4. Construct the following SQL statements in the
SELECT *FROM employee WHERE ALLOWANCE student table-
BETWEEN 5000 AND 7000; (i) SELECT statement using GROUP BY clause.
(iii) To remove the employees who are mechanic. The GROUP BY statement groups rows that have the
DELETE FROM employee WHERE DESIG=”Mechanic”; same values.
(iv) To add a new row. The GROUP BY statement is often used with aggregate
INSERT INTO employee VALUES functions.
(“M1006”,”Rajesh”,”Mechanic”,20000,7000); For example- To count the number of male and female
(v) To display the details of all employees who are students in the student table, the following command
operators. is given :
SELECT *FROM employee WHERE DESIG=”Operator”; SELECT Gender, count(*) FROM Student GROUP BY
Gender;
(ii) SELECT statement using ORDER BY clause.
3. What are the components of SQL? Write the
commands in each. The ORDER BY clause in SQL is used to sort the data in
either ascending or descending based on one or more
SQL commands are divided into five categories:
columns.
1) DDL - Data Definition Language
It consist of SQL statements used to define the For example: To display the students in alphabetical
database structure or schema. order of their names, the command is used as
CREATE - To create tables in the database. SELECT * FROM Student ORDER BY Name;
ALTER - Alters the structure of the database.
DROP - Deletes tables from database. 5. Write a SQL statement to create a table for
employee having any five fields and create a table
2) DML - Data Manipulation Language constraint for the employee table
DML is a query language used for adding , deleting,
and updating data in a database.

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 12


CREATE TABLE employee ( Ex.
empcode INTEGER NOT NULL, import csv
empname CHAR(20), F=open(“c:\pyprg\student.csv” , 'r')
desig CHAR(15), reader = csv.reader(F)
pay INTEGER, for row in reader:
allowance INTEGER, print(row)
PRIMAY KEY(empcode) F.close()
); Using the DictReader class
The csv.DictReader() method can be used to read a
CHAPTER 13 - PYTHON AND CSV FILES CSV file as a dictionary.
1. Differentiate Excel file and CSV file. Ex:
Excel CSV import csv
MS Excel stands for CSV stands for Comma F=open(“c:\pyprg\student.csv” , 'r')
Microsoft Excel. separated value. reader = csv.DictReader(F)
Excel is a binary file that It is a plain text format for row in reader:
holds information, with a series of values print( dict(row) )
including both content separated by commas. F.close()
and formatting.
Excel file can be opened CSV can be opened with
4. Write a Python program to write a CSV File with
with Microsoft Excel any text editor.
custom quotes.
only.
Excel file saved with CSV file saved with import csv
extension as .xls / .xlsx extension as .csv csv.register_dialect( ‘myDialect’ , quoting=csv.QUOTE_ALL)
It consumes more It consumes less memory. F= open(“c:\pyprg\student.csv”, “w”)
memory. writer = csv.writer(F, dialect=”myDialect”)
2. Tabulate the different mode with its meaning. writer.writerow( [‘Adno’, ‘Name, ‘Class’] )
Python File Modes writer.writerow([121, ‘Rajesh’, ‘XII-IC’] )
Mode Description F.close()
'r' Open a file for reading. (default)
'w' Open a file for writing. 5. Write the rules to be followed to format the data in
'x' Open a file for exclusive creation. a CSV file.
a' Open for appending at the end of the file. (i) Each record (row of data) is to be located on a
separate line.
't' Open in text mode. (default)
(ii) The last record in the file may or may not have an
'b' Open in binary mode. ending line break.
'+' Open a file for updating (reading and writing) (iii) There may be an optional header line appearing as
the first line of the file.
3. Write the different methods to read a File in (iv) Within the header and each record, there may be
Python. one or more fields, separated by commas.
There are two ways to read a CSV file. (v) Each field may or may not be enclosed in double
1. Using the csv module’s reader function quotes.
2. Using the DictReader class. (vi) Fields containing line breaks and commas should
CSV Module’s Reader Function be enclosed in double-quotes.
We can read the contents of CSV file with the help of
csv.reader() function. The syntax is,
csv.reader(fileobject, delimiter, parameters)

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 13


CHAPTER 14 - IMPORTING C++ PROGRAMS IN PYTHON The getopt Module
1. Write any 5 features of Python. The getopt module contains functions to extract
• Python uses Automatic Garbage Collection whereas command-line options and arguments.
C++ does not. This module provides getopt() method to enable
• C++ is a statically typed language, while Python is a command-line argument parsing.
dynamically typed language. It can handle both short and long option formats.
• Python runs through an interpreter, while C++ is pre- Syntax:
compiled. getopt.getopt ( args , options , [ long_options ] )
• Python code tends to be 5 to 10 times shorter than
that written in C++.
4. Write the syntax for getopt() and explain its
• In Python, there is no need to declare types explicitly arguments and return values
where as it should be done in C++
The getopt module of Python helps you to parse (split)
• In Python, a function may return multiple values. But command-line options and arguments.
in C++, a function can return only one value.
This module provides getopt() method to enable
2. Explain each word of the following command. command-line argument parsing.
python <filename.py> -<i> <C++ filename without cpp Syntax:
extension>
getopt.getopt ( args , options , [ long_options ] )
python keyword to execute the Python
args: The args is the list of arguments which are to be
program from commandline
passed
filename.py Name of the Python program to options: The options are the string of options letters
executed which should be written with a colon ( :).
-i input mode long_options: This is the list of the string which have
C++ filename name of C++ file to be compiled the name of long options should be written with an
without and executed equal sign ( = ).
cpp extension Return Type: The first element of the return value is
the list of ( option , value ) pairs, and the second
3. What is the purpose of sys, os, getopt modules in element of the return value is a list of program
Python. Explain arguments which are left.
sys module Ex: opts, args = getopt.getopt (argv, "i:",['ifile='])
This module provides access to built-in variables used
by the interpreter. 5. Write a Python program to execute the following
One among the variable in sys module is argv c++ coding
sys.argv is the list of command-line arguments passed #include <iostream>
to the Python program. using namespace std;
To use sys.argv, import sys should be used. The first int main()
argument, sys.argv[0] contains the name of the { cout<<“WELCOME”;
python program.
return(0);
OS Module
}
The OS module in Python provides functions for
The above C++ program is saved in a file welcome.cpp
interacting with the operating system.
import os
The os.system() method executes the command in a
subshell. argv = sys.argv[1:]
os.system(command) cppfile = ''
Example to find the current date of computer: exefile = ''
import os
print (os.system('date')) opts, args = getopt.getopt(argv, "i:o:", ["ifile="])

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 14


for opt, arg in opts: This is similar to WHERE condition but can be used only
if opt == '-i': with group functions.
cppfile = arg+".cpp" import sqlite3
elif opt == '-o': connection = sqlite3.connect("school.db")
exefile = arg+".exe" cursor = connection.cursor()
cursor.execute("SELECT GENDER,COUNT(GENDER) FROM
Student GROUP BY GENDER HAVING COUNT(GENDER)>3")
os.system('g++ ' + cppfile + ' -o ' + exefile)
result = cursor.fetchall( )
os.system(exefile)
print(result)
4. Write a Python script to create a table called ITEM
CHAPTER 15 DATA MANIPULATION THROUGH SQL with following specification. Add one record to the
1. Write in brief about SQLite and the steps used to table.
use it. Name of the database :- ABC
 SQLite is a simple relational database system. Name of the table :- Item
 It saves data in regular data files within internal Column name and specification :-
memory of the computer. Icode :- integer and act as primary key
 It is designed to be embedded in applications. Item Name :- Character with length 25
 SQLite is fast and flexible, making it easier to Rate :- Integer
work. Record to be added :- 1008, Monitor,15000
 Python has a native library for SQLite. import sqlite3
To use SQLite, connection = sqlite3 . connect ("ABC.db")
Step 1 : import sqlite3 cursor = connection . cursor ()
Step 2 : create a connection using connect () method. qry = ” CREATE TABLE Item (Icode INTEGER, Item_Name
Step 3 : Set the cursor object cursor = connection. VARCHAR (25), Rate Integer);”
cursor () cursor.execute (qry)
2. Write the Python script to display all the records of qry = “INSERT INTO Item VALUES (1008, ‘Monitor’,
the following table using fetchmany() 15000);”
Icode ItemName Rate cursor.execute (qry)
1003 Scanner 10500 connection.commit ()
1004 Speaker 3000 connection.close ()
1005 Printer 8000
1008 Monitor 15000 5. Consider the following table Supplier and item
1010 Mouse 700 .Write a python script for (i) to (ii)
Suppno Name City Icode SuppQty
Python Script: S001 Prasad Delhi 1008 100
import sqlite3 S002 Anu Bangalore 1010 200
connection = sqlite3.connect ("shop.db") S003 Shahid Bangalore 1008 175
cursor = connection . cursor () S004 Akila Hydrabad 1005 195
cusrsor. execute ("SELECT * FROM stock") S005 Girish Hydrabad 1003 25
result = cursor. fetchmany (5) S006 Shylaja Chennai 1008 180
print(*result,sep=”\n”) S007 Lavanya Mumbai 1005 325
i) Display Name, City and Item name of suppliers who
3. What is the use of HAVING clause. Give an example do not reside in Delhi.
python script. ii) Increment the SuppQty of Akila by 40
Having clause is used to filter data based on the group
functions.

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 15


(i) import sqlite3 Example
connection = sqlite3.connection ("supplier.db") import matplotlib.pyplot as plt
cursor = connection.cursor () subjects = ["TAMIL", "ENGLISH", "MATHS"]
cursor.execute ("SELECT Name, City, Icode FROM Item marks = [80, 60, 85]
WHERE City <> "Delhi") plt.pie (marks,labels=subjects, autopct = "%.2f")
result = cursor.fetchall () plt.show()
print (* result, sep = "\n")
(ii) import sqlite3 2. Explain the various buttons in a matplotlib window.
conn = sqlite3.connect ("supplier.db") (i) Home Button j The Home Bukon will help one to
begun navigating the chart. If you ever want to return
conn.execute ("UPDATE Item SET Name = ‘Akila’ WHERE
back to the original view, you can click on this.
SuppQty = 235)
(ii) Forward/Back buttons j These bukons can be
conn.commit ()
used like the Forward and Back buttons in browser.
cursor = conn.execute ("SELECT * FROM Item") Click these to move back to the previous point you
for row in cursor: were at, or forward again.
print (row) (iii) Pan Axis j This cross-looking button allows you to
conn.close () click it, and then click and drag graph around.
(iv) Zoom j The Zoom bukon lets you click on it, then
CHAPTER 16 DATA VISUALIZATION USING PYPLOT click and drag a square would like to zoom into
specifically. Zooming in will require a left click and
1. Explain in detail the types of pyplots using
drag. Zoom out with a right click and drag.
Matplotlib.
(v) Configure Subplots j This bukon allows you to
Line Chart
configure various spacing options with figure and plot.
A Line Chart or Line Graph is a type of chart which
displays information as a series of data points
connected by straight line segments. 3. Explain the purpose of the following functions: a.
plt.xlabel b. plt.ylabel c. plt.title d. plt.legend() e.
Example:
plt.show()
import matplotlib.pyplot as plt
a. plt.xlabel - Specifies label for x-axis
plt.plot([1,2,3,4], [1,4,9,16])
b. plt.ylabel - Specifies label for y-axis
plt.show()
c. plt.title - Specifies title to the graph.
Bar Chart
d. plt.legend() - Places a legend on various types of
A BarChart is one of the most common type of plot. graphs.
It shows the relationship between a numerical data e. plt.show() - Displays the plot.
and a categorical values.
----- & -----
Bar chart represents data with rectangular bars.
Example:
import matplotlib.pyplot as plt
Prepared by:
subjects = ["TAMIL", "ENGLISH", "MATHS"] S.Ganesh Kumar, B.Sc.,B.Ed.,M.S.I.T.,
marks = [80, 60, 85]
plt.bar (subjects, marks)
N.S.Hr.Sec.School, Theni.
plt.show() (for any suggestions please mail to
Pie Chart [email protected])
Pie Chart is probably one of the most common type of Also available at www.scribd.com/rsgk
chart.
It is a circular graphic which is divided into slices to
illustrate numerical proportion.

N.S.Hr.Sec.School, Theni S.Ganesh Kumar, B.Sc., B.Ed., M.S.I.T., 16

You might also like