CS Knowledge Opener for 12th Grade
CS Knowledge Opener for 12th Grade
[Link] 1 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
PROVERB
As Nelson Mandela says,
“Education is the most powerful weapon which you can use to change the world.”
As Bill Gates says,
“Don’t compare yourself with anyone in this world… if you do so, you are insulting yourself.”
• “CS KNOWLEDGE OPENER” Computer Science for standard XII has been prepared
in accordance with the New Textbook released by the Government of Tamil Nadu.
• Each chapter consists of an Important Terms / Definition and Answers to the Textbook
Questions, which gives a summary of the concepts presented in the text in a simple and
lucid language.
• It is hoped that this book in the present form will satisfy all types of learners and help them
improve their learning potential, apart from mentally preparing them to face any type of
questions in the examinations.
• This Study Material is prepared from Re-Print Text Book 2024
• Our aim is to make all the students who study this study material to score high marks in
theory.
PUBLIC QUESTION PATTERN (THEORY)
Out of 9
PART – II Answer any Six Questions. Question No.24 Compulsory 6x2=12
Questions
Out of 9
PART – III Answer any Six Questions. Question No.33 Compulsory 6x3=18
Questions
OR Type
PART – IV Answer all the Questions 5x5=25
Questions
TOTAL 70
PUBLIC PRACTICAL PATTERN
Internal Marks 15
External Marks
15
TOTAL 30
[Link] 2 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
TABLE OF CONTENTS
COMPUTER SCIENCE – II YEAR
1 FUNCTION
UNIT – I
2 DATA ABSTRACTION
PROBLEM SOLVING
TECHNIQUES
3 SCOPING
4 ALGORITHMIC STRATEGIES
6 CONTROL STRUCTURES
UNIT – II
CORE PYTHON
7 PYTHON FUNCTION
11 DATABASE CONCEPTS
UNIT – IV
DATABASE
12 STRUCTURED QUERY LANGUAGE(SQL)
CONCEPTS AND
MYSQL
13 PYTHON AND CSV FILES
[Link] 3 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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
[Link] 4 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 5 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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’
[Link] 6 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 7 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 8 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 9 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 10 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 11 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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
[Link] 12 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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).
[Link] 14 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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
[Link] 15 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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
[Link] 16 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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.
[Link] 18 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
Portable An algorithm should be generic, independent and able to handle all range of inputs.
[Link] 19 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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
[Link] 20 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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.
[Link] 21 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 22 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 23 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
• 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.
[Link] 25 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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
[Link] 26 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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
[Link] 27 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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:"))
[Link] 29 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 30 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 31 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 32 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 33 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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([Link] (5.5)) print([Link] (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"))
[Link] 34 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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>
[Link] 35 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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
[Link] 36 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 37 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 38 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 40 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 41 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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 [Link](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.
[Link] 42 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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
>>>
[Link] 43 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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 : [Link](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'] [Link]( )
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.
[Link] 44 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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:
[Link] (position index, element)
Example:
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar']
>>> [Link](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:
[Link] (element to be added)
Example:
>>> Mylist=[34, 45, 48]
>>> [Link](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:
[Link] ( [elements to be added])
Example:
>>> Mylist=[34, 45, 48]
>>> [Link]([71, 32, 29])
[Link] 45 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
>>> 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.
[Link] 46 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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'}
[Link] 47 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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
[Link] 48 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 49 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 50 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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 [Link]
[Link]()
OUTPUT:
Fruit 1 = Apple, Fruit 2 = Mango
ERROR:
line 8, in <module>
del [Link]
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')
[Link]()
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')
[Link]()
Output:
>>>
Good Morning Bindu Madhavan
>>>
[Link] 51 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 53 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 54 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 55 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• Example:
Example:
[Link] 57 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
• 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.
[Link] 59 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 60 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 61 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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).
[Link] 62 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 63 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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
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),
[Link] 64 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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=[Link](open('c:\PYPRG\ch13\[Link]'))
next(d)
for row in d:
print(row)
if the file called “[Link]” 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 [Link] using the following program import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator = '\n')
with open('c:\pyprg\ch13\[Link]', 'w') as f:
wr = [Link](f,dialect='M')
[Link](D)
[Link]()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
(C) E (D) Exam,
Q Quarterly,
H Halfyearly
[Link] 65 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
lines = list(reader)
lines[3] = row
with open(‘[Link]’, ‘w’) as writeFile:
writer = [Link](writeFile)
[Link](lines)
[Link]()
[Link]()
3. Write a Python program to read a CSV file with default delimiter comma (,).
Program:
import csv
with open('c:\\pyprg\\[Link]', 'r') as F:
reader = [Link](F)
print(row)
[Link]()
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/[Link]():
• 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.
• [Link] 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 • CSV format is a plain text format with a series
about all the worksheets in a file, including both of values separated by commas.
content and formatting.
[Link] 67 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• XLS files can only be read by applications that • CSV can be opened with any text editor in
have been especially written to read their Windows like notepad, MS Excel, OpenOffice,
format, and can only be written in the same way. etc.
• Excel is a spreadsheet that saves files into its • CSV is a format for saving tabular information
own proprietary format viz. xls or xlsx into a delimited text file with extension .csv
• Excel consumes more memory while importing • Importing CSV files can be much faster, and it
data also consumes less memory
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).
[Link] work with dictionary.
[Link] take additional argument field names that are used as dictionary keys.
Example:
import csv
filename = ‘c: \pyprg\[Link]’
input_file =[Link](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\\[Link]’, ‘w’) as f:
writer = [Link](f, dialect=’myDialect’)
for row in info:
[Link](row)
[Link]()
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.
[Link] 69 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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:
[Link] 70 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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
• Data type is not required while declaring • Data type is required while declaring variable
variable
[Link] 71 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• It can act both as scripting and general purpose • It is a general purpose language
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: [Link]()
Welcome Module name
. Dot operator
display() Function call
5. What is [Link]? What does it contain?
• [Link] 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 [Link], you will first have to import sys.
• [Link][0] is always the name of the program as it was invoked.
• [Link][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 <[Link]> -<i> <C++ filename without cpp extension>
Where ,
Python Keyword to execute the Python program from command-line
<[Link] > Name of the Python program to executed
-< i > Input mode
<C++ filename without cpp Name of C++ file to be compiled and executed
extension>
[Link] 72 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 73 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
• [Link] method:
This method parses command-line options and parameter list.
• Syntax of getopt method:
<opts>,<args>=[Link](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 = [Link] (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 [Link]
PYTHON PROGRAM:
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = [Link](argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
[Link] 74 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
exe_file = a + '.exe'
run(cpp_file, exe_file)
def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
[Link]('g++ ' + cpp_file + ' -o ' + exe_file)
print("Running " + exe_file)
print("-----------------------")
print
[Link](exe_file)
print
if __name__ =='__main__': #program starts executing from here
main([Link][1:])
STEPS TO IMPORT CPP CODE INTO PYTHON CODE:
Select File→New in Notepad and type the above Python program.
Save the File as [Link].
Click the Run Terminal and open the command window
Go to the folder of Python using cd command.
Type the command: Python c:\pyprg\[Link] -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
[Link] 75 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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 = [Link] ("[Link]")
cursor = [Link]()
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");"""
[Link](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:
[Link]("SELECT * FROM student")
print([Link]())
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().
[Link] 76 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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 = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = [Link]()
print(*result,sep="\n")
OUTPUT:
('B',)
('A',)
('C',)
('D',)
4. Read the following [Link] on that write a python script to display department wise
records.
database name :- [Link]
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = [Link](“[Link]”)
c=[Link](“SELECT * FROM Employee GROUP BY Dept”)
for row in c:
print(row)
[Link]()
5. Read the following [Link] on that write a python script to display records in
desending order of Eno.
database name :- [Link]
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = [Link](“[Link]”)
cursor=[Link]()
[Link](“SELECT * FROM Employee ORDER BY Eno DESC”)
result=[Link]()
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.
[Link] 77 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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=[Link]("[Link]")
cursor=[Link]( )
• 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 = [Link](“[Link]”)
cursor=[Link]()
[Link](“SELECT * FROM Materials”)
print(“Displaying All The Records”)
result=[Link](5)
print(result, Sep= “\n”)
[Link] 78 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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 = [Link]("[Link]")
cursor = [Link]()
[Link]("SELECT GENDER,COUNT(GENDER) FROM Student GROUP BY GENDER HAVING
COUNT(GENDER)>3")
result = [Link]()
co = [i[0] for i in [Link]]
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 = [Link](“[Link]”)
cursor=[Link]()
sql_command – “““ CREATE TABLE Item(
Icode INTEGER PRIMARY KEY,
ItemName VARCHAR(25),
Rate INTEGER) ; ”””
[Link](sql_command)
sql_command = “““ INSERT INTO Item(Icode, ItemName, Rate) VALUES (1008, ‘Monitor’, 15000);
”””
[Link] 79 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link](sql_command)
[Link]()
[Link]()
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 = [Link](“[Link]”)
[Link](“SELECT [Link], [Link],[Link] FROM Supplier,Item
WHERE [Link] = [Link] AND [Link] NOT In Delhi ”)
s = [i[0] for I in [Link]]
print(s)
result = [Link]()
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 = [Link](“[Link]”)
[Link](“UPDATE Supplier ST SuppQty = SuppQty +40 WHERE Name = ‘Akila’ ”)
[Link]()
result = [Link]()
print (result)
[Link]()
[Link] 80 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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. [Link] b. [Link] c. [Link] d. [Link]
2. Identify the package manager for installing python packages, or modules.
a. Matplotlib b. PIP c. [Link]() 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 [Link] as plt
b. [Link](3,2)
c. [Link]()
Identify the output for the above coding.
[Link] 81 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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 [Link] as plt
• Matplotlib can be imported in the workspace.
5. Write the difference between the following functions:
[Link]([1,2,3,4]), [Link]([1,2,3,4], [1,4,9,16]).
[Link] 82 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
OUTPUT:
Program:
import [Link] as plt
slices=[29.2,8.3,8.3,54.2]
activities=['sleeping','eating', 'working','playing']
cols=['c','m','r','b']
[Link](slices, labels=activities, colors=cols,startangle=90, shadow=True,
explode=(0,0.1,0,0),autopct='%.2f')
[Link]('Interesting Graph \n Check it out')
[Link]()
[Link] 83 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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 [Link]() 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.
[Link] 84 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
• 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 [Link]() function.
• The autopct parameter allows us to display the percentage value using the Python string formatting.
Example:
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.
[Link] 85 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
PREPARED BY
[Link] 86 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 87 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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, [Link]
3. PIP COMMAND
• Open Command Prompt, Type the command given below.
• python -m pip install -U pip
• pip install matplotlib
[Link] 88 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
INDEX
QUESTION
[Link] PROGRAM NAME
NUMBER
[Link] 89 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 90 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 91 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 92 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 93 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 94 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
RESULT:
Thus the Python program to generate prime numbers and set operations has been done and
the output is verified.
[Link] 95 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
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.
[Link] 97 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 98 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
[Link] 99 [Link]
J. ILAKKIA [Link]., [Link]., [Link]. Computer Instructor Grade-I, GHSS – [Link], Villupuram.
RESULT:
Thus the MySQL employee table has been done and the output is verified.
Data to be entered
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.
RESULT:
Thus the MySQL student table has been done and the output is verified.
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.
RESULT:
Thus the Python with SQL has been done and the output is verified.
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
[Link] Mark = 73
RESULT:
Thus the Python graphics with pip has been done and the output is verified.