Xii - Cs em Study Material 2025-2026
Xii - Cs em Study Material 2025-2026
https://csknowledgeopener.com 1 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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 2025
• 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
https://csknowledgeopener.com 2 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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
https://csknowledgeopener.com 3 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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
https://csknowledgeopener.com 4 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 6 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
➢ gcd b (a mod b)
v) Statement which terminates the recursion
➢ return a
3. Explain with example Pure and impure functions.
Pure Function Impure Function
• Pure functions will give exact result when the • Impure functions never assure you that the
same arguments are passed. function will behave the same every time it’s
called.
• Pure function does not cause any side effects to • Impure function causes side effects to its
its output. output.
• The return value of the pure functions solely • The return value of the impure functions does
depends on its arguments passed. not solely depend on its arguments passed.
• They do not modify the arguments which are • They may modify the arguments which are
passed to them passed.
• If we call pure functions with same set of • If we call impure functions with same set of
arguments, we will always get the same return arguments, we might get the different return
values. values.
Example: sqrt() • Example: random()
let square x:= let random number:=
return: x * x a := random()
if a > 10 then
return: a
else
return: 10
➢ Example:
https://csknowledgeopener.com 7 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 8 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 9 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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
• Here the variable ‘a’ is mapped to the value ‘5’.
5. How Python represents the private and protected Access specifiers?
https://csknowledgeopener.com 12 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
• Python prescribes a convention of adding a prefix __(double underscore) results in a variable name or
method becoming private.
• Example: self.__n2=n2
• Adding a prefix _ (single underscore) to a variable name or method makes it protected.
• Example: self._sal = sal
Section-C
Answer the following questions (3 Mark)
1. Define Local scope with an example.
• Local scope refers to variables defined in current function.
• A function will always look up for a variable name in its local scope.
• Only if it does not find it there, the outer scopes are checked.
• Example:
Disp( ):
a := 7 → Local Scope
print a
Disp( )
• OUTPUT: 7
2. Define Global scope with an example.
• A variable which is declared outside of all the functions in a program is known as global variable.
• Global variable can be accessed inside or outside of all the functions in a program.
• Example:
a:=10 → Global Scope
Disp( )
a := 7 → Local Scope
print a
Disp( )
print a
❖ OUTPUT:
7
10
3. Define Enclosed scope with an example.
• A function (method) with in another function is called nested function
• A variable which is declared inside a function which contains another function definition with in it, the
inner function can also access the variable of the outer function. This scope is called enclosed scope.
• When a compiler or interpreter searches for a variable in a program, it first search Local, and then search
Enclosing scopes.
❖ EXAMPLE:
Disp( ):
a:=10
Disp1( ):
print a
Disp1( )
print a
Disp( ):
https://csknowledgeopener.com 13 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
❖ 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).
https://csknowledgeopener.com 14 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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
https://csknowledgeopener.com 15 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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
https://csknowledgeopener.com 16 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 18 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
Portable An algorithm should be generic, independent and able to handle all range of inputs.
https://csknowledgeopener.com 19 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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
https://csknowledgeopener.com 20 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
• Dynamic programming is used when the solution to a problem can be viewed as the result of a sequence
of decisions.
• Dynamic programming approach is similar to divide and conquer (i.e) the problem can be divided into
smaller sub-problems.
• Results of the sub-problems can be re-used to complete the process.
• Dynamic programming approaches are used to find the solution in optimized way.
Steps to do Dynamic programming
• The given problem will be divided into smaller overlapping sub-problems.
• An optimum solution for the given problem can be achieved by using result of smaller sub-problem.
• Dynamic algorithms uses Memoization.
Fibonacci Iterative Algorithm with Dynamic Programming Approach
• The following example shows a simple Dynamic programming approach for the generation of Fibonacci
series.
• Initialize f0=0, f1 =1
• step-1: Print the initial values of Fibonacci f0 and f1
• step-2: Calculate fibanocci fib ← f0 + f1
• step-3: Assign f0← f1, f1← fib
• step-4: Print the next consecutive value of fibanocci fib
• step-5: Goto step-2 and repeat until the specified number of terms generated
• For example if we generate fibonacci series upto 10 digits, the algorithm will generate the series as
shown below:
• The Fibonacci series is : 0 1 1 2 3 5 8 13 21 34 55
5. PYTHON - VARIABLES AND OPERATORS
Section – A
Choose the best answer (1 Mark)
1. Who developed Python ?
A) Ritche B) Guido Van Rossum C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept instruction.
A) >>> B) <<< C) # D) <<
3. Which of the following shortcut is used to create new Python Program ?
A) Ctrl + C B) Ctrl + F C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program ?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($) C) comma(,) D) Colon(:)
6. Which of the following is not a token ?
A) Interpreter B) Identifiers C) Keyword D) Operators
7. Which of the following is not a Keyword in Python ?
A) break B) while C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or C) not D) Assignment
Section-B
Answer the following questions (2 Mark)
1. What are the different modes that can be used to test Python Program ?
• Two modes of Python programming are,
• Interactive mode allows us to write codes in Python command prompt ( >>> ).
• Script mode is used to create and edit python source file with the extension .py
2. Write short notes on Tokens.
• Python breaks each logical line into a sequence of elementary lexical components known as Tokens.
• The normal token types are ,
1) Identifiers
2) Keywords
3) Operators
4) Delimiters
5) Literals
3. What are the different operators that can be used in Python ?
• Operators are special symbols which represent computations, conditional matching in programming.
• Operators are categorized as Arithmetic, Relational, Logical, Assignment and Conditional.
4. What is a literal? Explain the types of literals ?
• Literal is a raw data given in a variable or constant.
• In Python, there are various types of literals. They are,
1) Numeric Literals consists of digits
2) String literal is a sequence of characters surrounded by quotes.
3) Boolean literal can have any of the two values: True or False.
5. Write short notes on Exponent data?
• An Exponent data contains decimal digit part, decimal point, exponent part followed by one or more digits.
• Example: 12.E04, 24.e04
Section-C
Answer the following questions (3 Mark)
1. Write short notes on Arithmetic operator with examples.
• An arithmetic operator is a mathematical operator used for simple arithmetic.
• It takes two operands and performs a calculation on them.
• Arithmetic Operators used in python:
• Example:
a=5 # assigns the value 5 to a
a+=2 # a=a+2, add 2 to the value of ‘a’ and stores the result in ‘a’.
3. Explain Ternary operator with examples.
• Ternary operator is also known as conditional operator that evaluates something based on a condition
being true or false.
• It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
Syntax:
Variable Name = [on_true] if [Test expression] else [on_false]
Example :
min = 50 if 49<50 else 70 # Output: min = 50
4. Write short notes on Escape sequences with examples.
• In Python strings, the backslash "\" is a special character, also called the "escape" character.
• It is used in representing certain whitespace characters.
• Python supports the following escape sequence characters.
• “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.
• 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: ”))
https://csknowledgeopener.com 25 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 26 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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
2. elif can be considered to be abbreviation of
A) nested if B) if..else C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control C) Structure D) Indentation
4. Which statement is generally used as a placeholder?
https://csknowledgeopener.com 27 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 28 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
• 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:"))
if(x>=y)and(x>=z):
biggest=x
elif(y>=z):
biggest=y
https://csknowledgeopener.com 29 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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.
• 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
https://csknowledgeopener.com 30 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
Output :
Enter the first number:3
Enter the second number:6
Enter the third number:4
The biggest number is 6
https://csknowledgeopener.com 31 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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.
(a) I is correct and II is wrong
(b) Both are correct
(c) I is wrong and II is correct
(d) Both are wrong
9. Pick the correct one to execute the given statement successfully.
if ____ : print(x, " is a leap year")
https://csknowledgeopener.com 32 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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 to
equal to x x
Example: Example:
import math import math
print(math.ceil (5.5)) print(math.floor (5.5))
Output: Output:
6 5
5. Write a Python code to check whether a given year is leap year or not.
CODE:
n=int(input("Enter the year"))
if(n%4==0):
print ("Leap Year")
else:
print ("Not a Leap Year")
Output:
Enter the year 2012
https://csknowledgeopener.com 34 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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>
• 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.
https://csknowledgeopener.com 35 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
• 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
def loc():
y=0 # local scope
print(y)
loc()
Output: 0
➢ Global Scope
• A variable, with global scope can be used anywhere in the program.
• It can be created by defining a variable outside the scope of any function/block.
➢ Rules of global Keyword
The basic rules for global keyword in Python are:
• When we define a variable outside a function, it’s global by default. You don’t have to use global
keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect
Use of global Keyword
• Without using the global keyword we cannot modify the global variable inside the function but we can
only access the global variable.
Example:
x=0
def add():
global x
x=x+5
add()
print ("Global X :", x)
Output:
Global X : 5
3. Explain the following built-in functions.
(a) id() (b) chr() (c) round() (d) type() (e) pow()
https://csknowledgeopener.com 37 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 38 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 40 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 41 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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
(iv) String slicing
• Slice is a substring of a main string.
• A substring can be taken from the original string by using [ ] slicing operator and index values.
• Using slice operator, you have to slice one or more substrings from a main string.
General format of slice operation:
str[start:end]
• Where start is the beginning index and end is the last index value of a character in the string.
• Python takes the end value less than one from the actual index specified.
Example: slice a single character from a string
>>> str1="THIRUKKURAL"
>>> print (str1[0])
Output: T
(v) Stride when slicing string
• When the slicing operation, you can specify a third argument as the stride, which refers to the number of
characters to move forward after the first character is retrieved from the string.
• The default value of stride is 1.
• Python takes the last value as n-1
• You can also use negative value as stride, to prints data in reverse order.
Example:
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
>>> print(str1[::-2])
Output: Learn
nhy re teolW
https://csknowledgeopener.com 42 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 43 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
• Key=myFunc; “myFunc” - the name of the user defined function that specifies the sorting criteria.
3. What will be the output of the following code?
list = [2**x for x in range(5)]
print(list)
OUTPUT: [1, 2, 4, 8, 16]
4. Explain the difference between del and clear( ) in dictionary with an example.
del clear( )
The del statement is used to delete known elements The function clear( ) is used to delete all the
elements in list
The del statement can also be used to delete entire It deletes only the elements and retains the list.
list.
Example: Example:
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Age' : Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Age' :
18} 18}
del Dict['Age'] Dict.clear( )
print (Dict) print(Dict)
Output: {'Roll No' : 12001, 'SName' : 'Meena'} Output: { }
5. List out the set operations supported by python.
Set Operations:
(i) Union: It includes all elements from two or more sets.
(ii) Intersection: It includes the common elements in two sets.
(iii) Difference: It includes all elements that are in first set (say set A) but not in the second set (say set B).
iv) Symmetric difference: It includes all the elements that are in two sets (say sets A and B) but not the one
that are common to two sets.
6. What are the difference between List and Dictionary?
List Dictionary
• List is an ordered set of elements. • Dictionary is a data structure that is used for
matching one element (Key) with another
(Value).
• The index values can be used to access a • In dictionary key represents index.
particular element.
• Lists are used to look up a value. • It is used to take one value and look up
another value.
Section - D
Answer the following questions: (5 Mark)
1. What the different ways to insert an element in a list. Explain with suitable example.
Inserting elements in a list using insert():
• The insert( ) function is used to insert an element at desired position of a list.
Syntax:
List.insert (position index, element)
Example:
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar']
>>> MyList.insert(3, 'Rama')
>>> print(MyList)
https://csknowledgeopener.com 45 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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.
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.
https://csknowledgeopener.com 47 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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'}
print(set_A & set_B)
Output:
{'A', 'D'}
(iii) Difference:
• It includes all elements that are in first set (say set A) but not in the second set (say set B).
• The minus (-) operator is used to difference set operation in python.
• The function difference( ) is also used to difference operation.
Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
https://csknowledgeopener.com 48 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
{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
3. Class members are accessed through which operator?
(a) & (b) . (c) # (d) %
4. Which of the following method is automatically executed when an object is created?
(a) __object__( ) (b) __del__( ) (c) __func__( ) (d) __init__( )
5. A private class variable is prefixed with
(a) __ (b) && (c) ## (d) **
6. Which of the following method is used as destructor?
(a) __init__( ) (b) __dest__( ) (c) __rem__( ) (d) __del__( )
7. Which of the following class declaration is correct?
(a) class class_name (b) class class_name<> (c) class class_name: (d) class class_name[ ]
8. Which of the following is the output of the following program?
class Student:
def __init__(self, name):
self.name=name
S=Student(“Tamil”)
(a) Error (b) Tamil (c) name (d) self
9. Which of the following is the private class variable?
(a) __num (b) ##num (c) $$num (d) &&num
Section-B
Answer the following questions (2 Mark)
1. What is class?
• Class is the main building block in Python.
• Class is a template for the object.
• Objects are also called as instances of a class or class variable.
2. What is instantiation?
• The process of creating object is called as “Class Instantiation”.
• Objects are also called as instances of a class.
Syntax:
Object_name = class_name( )
3. What is the output of the following program?
class Sample:
__num=10
def disp(self):
print(self.__num)
S=Sample()
S.disp()
print(S.__num)
OUTPUT:
>>>
10
line 7, in <module>
print(S.__num)
AttributeError: 'Sample' object has no attribute '__num'
https://csknowledgeopener.com 50 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
class Fruits:
def __init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple','Mango')
F.display()
OUTPUT:
Fruit 1 = Apple, Fruit 2 = Mango
4. What is the output of the following program?
CODE:
class Greeting:
def __init__(self, name):
self.__name = name
def display(self):
print("Good Morning ", self.__name)
obj=Greeting('Bindu Madhavan')
obj.display()
Output:
>>>
Good Morning Bindu Madhavan
>>>
5. How do define constructor and destructor in Python?
CONSTRUCTOR:
• “init” is a special function begin and end with double underscore in Python act as a Constructor.
• Constructor function will automatically executed when an object of a class is created.
General format of constructor:
def __init__(self, [args ……..]):
<statements>
DESTRUCTOR:
• Destructor is also a special method gets executed automatically when an object exit from the scope.
• In Python, __del__( ) method is used as destructor.
General format of destructor:
def __del__(self):
<statements>
Section - D
Answer the following questions: (5 Mark)
1. Explain about constructor and destructor with suitable example
Constructor:
❖ Constructor is the special function called “init” which act as a Constructor.
❖ This function will executes automatically when the object is created.
❖ It must begin and end with double underscore.
https://csknowledgeopener.com 52 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 54 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
σ Π
General Form: Example:
σ (R)
c
Π (STUDENT)
Example: course
σ = “Big Data” (STUDENT )
course
2. What is the role of DBA?
• Database Administrator or DBA is the one who manages the complete database management system.
• DBA takes care of the security of the DBMS, managing the license keys, managing user accounts and access
etc.
3. Explain Cartesian Product with a suitable example.
• Cross product is a way of combining two relations.
• The resulting relation contains, both relations being combined.
• This type of operation is helpful to merge columns from two relations.
• Example: A x B means A times B, where the relation A and B have different attributes.
4. Explain Object Model with example.
• Object model stores the data in the form of objects, attributes and methods, classes and Inheritance.
• This model handles more complex applications, such as Geographic information System (GIS), scientific
experiments, engineering design and manufacturing.
• It is used in file Management System.
• It represents real world objects, attributes and behaviors.
Data Model
A data model describes how the data can be represented and accessed from a software after complete
implementation
Types of Data Model
The different types of a Data Model are,
• Hierarchical Model
• Relational Model
• Network Database Model
• Entity Relationship Model
• Object Model
i). Hierarchical Model:
• In Hierarchical model, data is represented as a simple tree like structure form.
• This model represents a one-to-many relationship ie parent-child relationship.
• One child can have only one parent but one parent can have many children.
• This model is mainly used in IBM Main Frame computers.
• Example:
https://csknowledgeopener.com 56 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 57 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 58 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
• 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
https://csknowledgeopener.com 59 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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:
https://csknowledgeopener.com 61 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
Table Constraint
(i)Unique Constraint:
• This constraint ensures that no two rows have the same value in the specified columns.
• For example UNIQUE constraint applied on Admno of student table ensures that no two students have the
same admission number and the constraint can be used as:
• 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.
https://csknowledgeopener.com 62 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
• 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).
https://csknowledgeopener.com 63 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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),
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?
https://csknowledgeopener.com 65 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
10. What will be written inside the file test.csv using the following program import csv
D = [['Exam'],['Quarterly'],['Halfyearly']]
csv.register_dialect('M',lineterminator = '\n')
with open('c:\pyprg\ch13\line2.csv', 'w') as f:
wr = csv.writer(f,dialect='M')
wr.writerows(D)
f.close()
(A) Exam Quarterly Halfyearly (B) Exam Quarterly Halfyearly
(C) E (D) Exam,
Q Quarterly,
H Halfyearly
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.
OUTPUT:
['SNO', 'NAME', 'CITY']
['12101', 'RAM', 'CHENNAI']
['12102', 'LAVANYA', 'TIRUCHY']
['12103', 'LAKSHMAN', 'MADURAI']
4. What is the difference between the write mode and append mode.
Write Mode Append Mode
• 'w' • 'a'
• Open a file for writing. • Open for appending at the end of the file
without truncating it.
• Creates a new file if it does not exist or • Creates a new file if it does not exist.
truncates the file if it exists.
5. What is the difference between reader() and DictReader() function?
Reader():
• The reader function is designed to take each line of the file and make a list of all columns.
• Using this method one can read data from csv files of different formats like quotes (" "), pipe (|) and comma
(,).
• csv. Reader work with list/tuple.DictReader():
• DictReader works by reading the first line of the CSV and using each comma separated value in this line as
a dictionary key.
• DictReader is a class of csv module is used to read a CSV file into a dictionary.
• It creates an object which maps data to a dictionary.
• csv.DictReader work with dictionary.
Section - D
Answer the following questions: (5 Mark)
1. Differentiate Excel file and CSV file.
Excel CSV
• Excel is a binary file that holds information about • CSV format is a plain text format with a series of
all the worksheets in a file, including both content values separated by commas.
and formatting.
• 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 format, Windows like notepad, MS Excel, OpenOffice,
and can only be written in the same way. etc.
• Excel is a spreadsheet that saves files into its own • CSV is a format for saving tabular information
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
'x' • Open a file for exclusive creation. If the file already exists, the operation fails.
'a' • Open for appending at the end of the file without truncating it. Creates a new file if
it does not exist.
't' • Opren in text mode. (default)
'b' • Open in binary mode.
'+' • Open a file for updating (reading and writing)
3. Write the different methods to read a File in Python.
Read a CSV File Using Python:
There are two ways to read a CSV file.
1. Use the csv.reader() method.
2. Use the DictReader class.
Reader Function:
❖ You can read the contents of CSV file with the help of csv.reader() method.
❖ The reader function is designed to take each line of the file and make a list of all columns. Then, you
just choose the column you want the variable data for.
❖ Using this method one can read data from csv files of different formats like quotes (" "), pipe (|) and
comma (,).
❖ csv. reader and csv.writer work with list/tuple
The syntax for csv.reader() is
csv.reader(fileobject,delimiter,fmtparams)
where,
➢ file object :- passes the path and the mode of the file
➢ delimiter :- an optional parameter containing the standard dilects like , | etc can be omitted
➢ fmtparams: optional parameter which help to override the default values of the dialects can be omitted.
Example:
import csv
F = ('c:\pyprg\sample1.csv', 'r')
reader = csv.reader(F)
for row in reader:
print(row)
F.close()
DictReader class:
❖ To read a CSV file into a dictionary can be done by using DictReader class of csv Module.
❖ It works similar to the reader() class but creates an object which maps data to a dictionary.
❖ DictReader works by reading the first line of the CSV and using each comma separated value in this line
as a dictionary key.
❖ The columns in each subsequent row then behave like dictionary values and can be accessed
with the appropriate key (i.e. fieldname).
❖ csv.DictReader work with dictionary.
❖ csv.DictReader take additional argument field names that are used as dictionary keys.
Example:
import csv
filename = ‘c: \pyprg\sample1.csv’
input_file =csv.DictReader(open(filename,’r’))
https://csknowledgeopener.com 69 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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.
• 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:
https://csknowledgeopener.com 70 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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:
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.
https://csknowledgeopener.com 71 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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
• 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: welcome.display()
https://csknowledgeopener.com 72 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 73 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
• The functions that the OS module allows you to interface with the Windows operating system where Python
is running on.
• os.system(): Execute the C++ compiling command in the shell.
• For Example to compile C++ program g++ compiler should be invoked.
• Command: os.system (‘g++’ + <varaiable_name1> ‘-<mode>’ + <variable_name2>
• Example:
os.system('g++ ' + cpp_file + ' -o ' + exe_file) -- g++ compiler compiles the file cpp_file and –o
(output) send to exe_file
(iii) Python getopt Module:
• The getopt module of Python helps you to parse (split) command-line options and arguments.
• This module provides two functions to enable command-line argument parsing.
• getopt.getopt method:
➢ This method parses command-line options and parameter list.
• Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
➢ Here is the detail of the parameters −
➢ argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
➢ options -- This is string of option letters that the Python program recognize as, for
input or for output, with options (like ‘i’ or ‘o’) that followed by a colon (:).
Here colon is used to denote the mode.
➢ long_options -- This parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('=').
➢ In our program the C++ file name will be passed as string and ‘i’ also will be passed along with to
indicate it as the input file.
• getopt() method returns value consisting of two elements.
• Each of these values are stored separately in two different list (arrays) opts and args .
• Opts contains list of splitted strings like mode, path and args contains any string if at all not splitted because
of wrong path or mode.
• args will be an empty array if there is no error in splitting strings by getopt().
4. Write the syntax for getopt() and explain its arguments and return values.
Python getopt Module:
• The getopt module of Python helps you to parse (split) command-line options and arguments.
• This module provides two functions to enable command-line argument parsing.
• getopt.getopt method:
➢ This method parses command-line options and parameter list.
• Syntax of getopt method:
<opts>,<args>=getopt.getopt(argv, options, [long_options])
➢ Here is the detail of the parameters −
➢ argv -- This is the argument list of values to be parsed (splited). In our program
the complete command will be passed as a list.
➢ options -- This is string of option letters that the Python program recognize as, for
https://csknowledgeopener.com 74 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
input or for output, with options (like ‘i’ or ‘o’) that followed by a colon
(:). Here colon is used to denote the mode
➢ long_options -- This parameter is passed with a list of strings. Argument of Long options
should be followed by an equal sign ('=').
➢ In our program the C++ file name will be passed as string and ‘i’ also will be passed along with to
indicate it as the input file.
• getopt() method returns value consisting of two elements.
• Each of these values are stored separately in two different list (arrays) opts and args .
• Opts contains list of splitted strings like mode, path and args contains any string if at all not splitted because
of wrong path or mode.
• args will be an empty array if there is no error in splitting strings by getopt().
• Example:
• opts, args = getopt.getopt (argv, "i:",['ifile='])
5. Write a Python program to execute the following c++ coding.
C++ CODE:
#include <iostream>
using namespace std;
int main()
{ cout<<“WELCOME”;
return(0);
}
The above C++ program is saved in a file welcome.cpp
PYTHON PROGRAM:
import sys, os, getopt
def main(argv):
cpp_file = ''
exe_file = ''
opts, args = getopt.getopt(argv, "i:",['ifile='])
for o, a in opts:
if o in ("-i", "--ifile"):
cpp_file = a + '.cpp'
exe_file = a + '.exe'
run(cpp_file, exe_file)
def run(cpp_file, exe_file):
print("Compiling " + cpp_file)
• A NULL will be used as an input for this column, the NULL will be automatically converted into an
integer which will one larger than the highest value so far used in that column.
• If the table is empty, the value 1 will be used.
4. Write the command to populate record in a table. Give an example.
• To populate (add record) the table "INSERT" command is passed to SQLite. “execute” method executes
the SQL command to perform some action.
• Example:
sql_command = """INSERT INTO Student (Rollno, Sname, Grade, gender, Average, birth_date) VALUES
(NULL, "Akshay", "B", "M","87.8", "2001-12-12");"""
cursor.execute(sql_command)
5. Which method is used to fetch all rows from the database table?
• The fetchall() method is used to fetch all rows from the database table.
• Example:
cursor.execute("SELECT * FROM student")
print(cursor.fetchall())
Section-C
Answer the following questions (3 Mark)
1. What is SQLite?What is it advantage?
• SQLite is a simple relational database system, which saves its data in regular data files or even in the internal
memory of the computer.
ADVANTAGES:
• SQLite is fast, rigorously tested, and flexible, making it easier to work.
• Python has a native library for SQLite.
2. Mention the difference between fetchone() and fetchmany()
fetchone() fetchmany()
• The fetchone() method returns the next row of a • The fetchmany() method returns the next number
query result set or None in case there is no row left of rows (n) of the result set.
• Using while loop and fetchone() method we can • Displaying specified number of records is done by
display all the records from a table. using fetchmany().
3. What is the use of Where Clause. Give a python statement Using the where clause.
• The WHERE clause is used to extract only those records that fulfill a specified condition.
EXAMPLE: To display the different grades scored by male students from “student table”
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT DISTINCT (Grade) FROM student where gender='M'")
result = cursor.fetchall()
print(*result,sep="\n")
OUTPUT:
('B',)
('A',)
('C',)
('D',)
4. Read the following details.Based on that write a python script to display department wise
https://csknowledgeopener.com 77 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
records.
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“organization.db”)
c=conn.execute(“SELECT * FROM Employee GROUP BY Dept”)
for row in c:
print(row)
conn.close()
5. Read the following details.Based on that write a python script to display records in
desending order of Eno.
database name :- organization.db
Table name :- Employee
Columns in the table :- Eno, EmpName, Esal, Dept
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“organization.db”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Employee ORDER BY Eno DESC”)
result=cursor.fetchall()
print(result)
Section - D
Answer the following questions: (5 Mark)
1. Write in brief about SQLite and the steps used to use it.
• SQLite is a simple relational database system, which saves its data in regular data files or even in the internal
memory of the computer.
• 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.
https://csknowledgeopener.com 78 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
• To create a table in the database, create an object and write the SQL command in it.
Example:-
import sqlite3
connection=sqlite3.connect("organization.db")
cursor=connection.cursor( )
• For executing the command use the cursor method and pass the required sql command as a parameter.
• Many number of commands can be stored in the sql_comm and can be executed one after other.
• Any changes made in the values of the record should be saved by the commend "Commit" before closing
the "Table connection".
2. Write the Python script to display all the records of the following table using fetchmany()
Icode ItemName Rate
1003 Scanner 10500
1004 Speaker 3000
1005 Printer 8000
1008 Monitor 15000
1010 Mouse 700
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“Materials.db”)
cursor=connection.cursor()
cursor.execute(“SELECT * FROM Materials”)
print(“Displaying All The Records”)
result=cursor.fetchmany(5)
print(result, Sep= “\n”)
OUTPUT:
Displaying All The Records
(1003, ‘Scanner’, 10500)
(1004, ‘Speaker’, 3000)
(1005, ‘Printer’, 8000)
(1008, ‘Monitor’, 15000)
(1010, ‘Mouse’, 700)
3. What is the use of HAVING clause. Give an example python script
• Having clause is used to filter data based on the group functions.
• This is similar to WHERE condition but can be used only with group functions.
• Group functions cannot be used in WHERE Clause but can be used in HAVING clause.
• Example:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor()
cursor.execute("SELECT GENDER,COUNT(GENDER) FROM Student GROUP BY GENDER HAVING
COUNT(GENDER)>3")
result = cursor.fetchall()
https://csknowledgeopener.com 79 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
PYTHON SCRIPT:
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor=connection.cursor()
sql_command – “““ CREATE TABLE Item(
Icode INTEGER PRIMARY KEY,
ItemName VARCHAR(25),
Rate INTEGER) ; ”””
cursor.execute(sql_command)
sql_command = “““ INSERT INTO Item(Icode, ItemName, Rate) VALUES (1008, ‘Monitor’, 15000);
”””
cursor.execute(sql_command)
connection.commit()
connection.close()
print(“TABLE CREATED”)
OUTPUT:
TABLE CREATED
5. Consider the following table Supplier and item .Write a python script for (i) to (ii)
SUPPLIER
Suppno Name City Icode SuppQty
S001 Prasad Delhi 1008 100
S002 Anu Bangalore 1010 200
S003 Shahid Bangalore 1008 175
S004 Akila Hydrabad 1005 195
S005 Girish Hydrabad 1003 25
S006 Shylaja Chennai 1008 180
S007 Lavanya Mumbai 1005 325
PYTHON SCRIPT:
i) Display Name, City and Itemname of suppliers who do not reside in Delhi.
https://csknowledgeopener.com 80 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“SELECT Supplier.Name, Supplier.City,Item.ItemName FROM Supplier,Item
WHERE Supplier.Icode = Item.Icode AND Supplier.City NOT In Delhi ”)
s = [i[0] for I in cursor.description]
print(s)
result = cursor.fetchall()
for r in result:
print r
OUTPUT:
[‘Name’, ‘City’, ‘ItemName’]
[‘Anu’, ‘Bangalore’, ‘Scanner’]
[‘Shahid’, ‘Bangalore’, ‘Speaker’]
[‘Akila’, ‘Hyderabad’, ‘Printer’]
[‘Girish’, ‘Hyderabad’, ‘Monitor’]
[‘Shylaja’, ‘Chennai’, ‘Mouse’]
[‘Lavanya’, ‘Mumbai’, ‘CPU’]
ii) Increment the SuppQty of Akila by 40
import sqlite3
connection = sqlite3.connect(“ABC.db”)
cursor.execute(“UPDATE Supplier ST SuppQty = SuppQty +40 WHERE Name = ‘Akila’ ”)
cursor.commit()
result = cursor.fetchall()
print (result)
connection.close()
OUTPUT:
(S004, ‘Akila’, ‘Hyderabad’, 1005, 235)
16. DATA VISUALIZATION USING PYPLOT: LINE CHART, PIE CHART AND
BAR CHART
Section – A
Choose the best answer (1 Mark)
1. Which is a python package used for 2D graphics?
a. matplotlib.pyplot b. matplotlib.pip c. matplotlib.numpy d. matplotlib.plt
2. Identify the package manager for installing python packages, or modules.
a. Matplotlib b. PIP c. plt.show() d. python package
3. Which of the following feature is used to represent data and information graphically?
a. Data List b. Data Tuple c. Classes and Objects d. Data visualization
4. _____ is a collection of resources assembled to create a single unified visual display.
a. Interface b. Dashboard c. Objects d. Graphics
5. Which of the following modules should be imported to visualize data and information in python?
a. csv b. getopt c. mysql d. matplotlib
6. _____ is a type of chart which displays information as a series of data points connected by straight line
segments.
a. Line chart b. Pie chart c. Bar chart d. All the above
7. Read the code:
a. import matplotlib.pyplot as plt
https://csknowledgeopener.com 81 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
b. plt.plot(3,2)
c. plt.show()
Identify the output for the above coding.
https://csknowledgeopener.com 82 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
OUTPUT:
https://csknowledgeopener.com 83 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
Program:
import matplotlib.pyplot as plt
slices=[29.2,8.3,8.3,54.2]
activities=['sleeping','eating', 'working','playing']
cols=['c','m','r','b']
plt.pie(slices, labels=activities, colors=cols,startangle=90, shadow=True,
explode=(0,0.1,0,0),autopct='%.2f')
plt.title('Interesting Graph \n Check it out')
plt.show()
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:
https://csknowledgeopener.com 84 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
Bar Chart:
• A BarPlot (or BarChart) is one of the most common type of plot.
• It shows the relationship between a numerical variable and a categorical variable.
• Bar chart represents categorical data with rectangular bars.
• Each bar has a height corresponds to the value it represents.
• The bars can be plotted vertically or horizontally.
• It’s useful when we want to compare a given numeric value on different categories.
• To make a bar chart with Matplotlib, we can use the plt.bar() function
Example:
Pie Chart:
• Pie Chart is probably one of the most common type of chart.
• It is a circular graphic which is divided into slices to illustrate numerical proportion.
• The point of a pie chart is to show the relationship of parts out of a whole.
• To make a Pie Chart with Matplotlib, we can use the plt.pie() function.
• The autopct parameter allows us to display the percentage value using the Python string formatting.
Example:
https://csknowledgeopener.com 85 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
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.
3. Explain the purpose of the following functions:
a. plt.xlabel
plt.xlabel()→specifies label for X-axis
b. plt.ylabel
plt.ylabel()→specifies label for Y-axis
c. plt.title
plt.title() →specifies title to the graph
d. plt.legend()
Calling legend() with no arguments automatically fetches the legend handles and their associated labels.
e. plt.show()
Display a figure. When running in Python with its Pylab mode, display all figures and return to the
Python prompt.
PREPARED BY
J. ILAKKIA M.Sc., B.Ed., M.Phil.
Computer Instructor Grade-I
Govt. Hr. Sec. School
V.Pagandai, Villupuram 605 501
https://csknowledgeopener.com 86 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 87 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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, https://youtu.be/ozAVCkovZ4M
3. PIP COMMAND
• Open Command Prompt, Type the command given below.
• python -m pip install -U pip
• pip install matplotlib
https://csknowledgeopener.com 88 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
INDEX
QUESTION
SL.NO PROGRAM NAME
NUMBER
https://csknowledgeopener.com 89 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 90 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 91 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 92 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 93 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 94 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
RESULT:
Thus the Python program to generate prime numbers and set operations has been done and
the output is verified.
https://csknowledgeopener.com 95 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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.
https://csknowledgeopener.com 97 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, Villupuram.
https://csknowledgeopener.com 98 http://www.youtube.com/c/csknowledgeopener
J. ILAKKIA M.Sc., B.Ed., M.Phil. Computer Instructor Grade-I, GHSS – V.Pagandai, 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
5.Social Mark = 73
RESULT:
Thus the Python graphics with pip has been done and the output is verified.