Download as pdf or txt
Download as pdf or txt
You are on page 1of 54

HIGHER SECONDARY – SECOND YEAR

Supporting Material

COMPUTER SCIENCE

PREPARATION TEAM
V.G. RAMAKRISHNAN K. KANNAN
Karnataka Sanga Hr. Sec. School, Chennai Girls Hr. Sec. School,
T. Nagar, Chennai 600 017 Rotler Street, Chennai 600 112

N.V. GOWRISHANKAR A. SAGAR BABU


Chennai Girls Hr. Sec. School, SMB Jain Hr. Sec. School,
Nungambakkam, Chennai 600 034 T. Nagar, Chennai 600 017

K. LENIN SIVA SARAVANAN,


Chennai Girls Hr. Sec. School, Chennai Hr. Sec. School,
Saidapet, Chennai 600 015 M.G.R. Nagar, Chennai 600 083

CHENNAI EDUCATIONAL DISTRICT

1
HIGHER SECONDARY – SECOND YEAR
COMPUTER SCIENCE
CHAPTER 1
FUNCTION

PART – I
CHOOSE THE BEST ANSWER:
1. The small sections of code that are used to 6. Which of the following are mandatory to write the
perform a particular task is called type annotations in the function definition?
(A) Subroutines (B) Files (A) Curly braces (B) Parentheses
(C) Pseudo code (D) Modules (C) Square brackets (D) indentations

2. Which of the following is a unit of code that is 7. Which of the following defines what an object
often defined within a greater code structure? can do?
(A) Subroutines (B) Function (A) Operating System (B) Compiler
(C) Files (D) Modules (C) Interface (D) Interpreter

3. Which of the following is a distinct syntactic 8. Which of the following carries out the instructions
block? defined in the interface?
(A) Subroutines (B) Function (A) Operating System (B) Compiler
(C) Definition (D) Modules (C) Implementation (D) Interpreter

4. The variables in a function definition are called 9. The functions which will give exact result when
as same arguments are passed are called
(A) Subroutines (B) Function (A) Impure functions (B) Partial Functions
(C) Definition (D) Parameters (C) Dynamic Functions (D) Pure functions

5. The values which are passed to a function 10. The functions which cause side effects to the
definition are called arguments passed are called
(A) Arguments (B) Subroutines (A) Impure function (B) Partial Functions
(C) Function (D) Definition (C) Dynamic Functions (D) Pure functions

CHAPTER 2
DATA ABSTRACTION

1. Which of the following functions those build the


abstract data type? 5. The data type whose representation is known
(A) Constructors (B) Destructors are called
(C) recursive (D) Nested (A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
2. Which of the following functions that retrieve
information from the data type? 6. The data type whose representation is unknown
(A) Constructors (B) Selectors are called
(C) recursive (D) Nested (A) Built in datatype (B) Derived datatype
(C) Concrete datatype (D) Abstract datatype
3. The data structure which is a mutable ordered
sequence of elements is called 7. Which of the following is a compound structure?
(A) Built in (B) List (A) Pair (B) Triplet
(C) Tuple (D) Derived data (C) single (D) quadrat
4. A sequence of immutable objects is called
(A) Built in (B) List
(C) Tuple (D) Derived data

2
8. Bundling two values together into one can be (A) Tuples (B) Lists
considered as (C) Classes (D) quadrats
(A) Pair (B) Triplet
(C) single (D) quadrat 10. Which of the following is constructed by placing
expressions within square brackets?
9. Which of the following allow to name the various (A) Tuples (B) Lists
parts of a multi-item object? (C) Classes (D) quadrats

CHAPTER 3
SCOPING

6. The process of subdividing a computer program


1. Which of the following refers to the visibility of into separate sub-programs is called
variables in one part of a program to another (A) Procedural Programming
part of the same program? (B) Modular programming
(A) Scope (B) Memory (C) Event Driven Programming
(C) Address (D) Accessibility (D) Object oriented Programming

2. The process of binding a variable name with an 7. Which of the following security technique that
object is called regulates who can use resources in a
(A) Scope (B) Mapping computing environment?
(C) late binding (D) early binding (A) Password (B) Authentication
(C) Access control (D) Certification
3. Which of the following is used in programming
languages to map the variable and object? 8. Which of the following members of a class can
(A) :: (B) := (C) = (D) == be handled only from within the class?
(A) Public members (B) Protected members
4. Containers for mapping names of variables to (C) Secured members (D) Private members
objects is called
(A) Scope (B) Mapping 9. Which members are accessible from outside the
(C) Binding (D) Namespaces class?
(A) Public members (B) Protected members
5. Which scope refers to variables defined in (C) Secured members (D) Private members
current function?
(A) Local Scope (B) Global scope 10. The members that are accessible from within
(C) Module scope (D) Function Scope the class and are also available to its sub-
classes is called
(A) Public members (B) Protected members
(C) Secured members (D) Private members

CHAPTER 4
ALGORITHMIC STRATEGIES

1. The word comes from the name of a Persian 2. From the following sorting algorithms which
mathematician Abu Ja’far Mohammed ibn-i algorithm needs the minimum number of
Musa al Khowarizmi is called? swaps?
(A) Flowchart (B) Flow (A) Bubble sort (B) Quick sort
(C) Algorithm (D) Syntax (C) Merge sort (D) Selection sort

3
3. Two main measures for the efficiency of an 7. Time complexity of bubble sort in best case is
algorithm are (A) θ (n) (B) θ (nlogn)
(A) Processor and memory (C) θ (n2) (D) θ (n(logn) 2)
(B) Complexity and capacity
(C) Time and space (D) Data and space 8. The Θ notation in asymptotic evaluation
represents
4. The complexity of linear search algorithm is (A) Base case (B) Average case
(A) O(n) (B) O(log n) (C) Worst case (D) NULL case
(C) O(n2) (D) O(n log n)
9. If a problem can be broken into subproblems
5. From the following sorting algorithms which has which are reused several times, the problem
the lowest worst case complexity? possesses which property?
(A) Bubble sort (B) Quick sort (A) Overlapping subproblems
(C) Merge sort (D) Selection sort (B) Optimal substructure
(C) Memoization (D) Greedy
6. Which of the following is not a stable sorting
algorithm? 10. In dynamic programming, the technique of
(A) Insertion sort (B) Selection sort storing the previously calculated values is
(C) Bubble sort (D) Quick sort called?
(A) Saving value property
(B) Storing value property
(C) Memoization (D) Mapping

Chapter - 5
PYTHON - VARIABLES AND OPERATORS
1. Who developed Python?
(A) Ritche (B) Guido Van Rossum 6. Which of the following is not a token?
(C) Bill Gates (D) Sunder Pitchai (A) Interpreter (B) Identifiers
(C) Keyword (D) Operators
2. The Python prompt indicates that Interpreter is
ready to accept instruction. 7. Which of the following is not a Keyword in
(A) >>> (B) <<< Python?
(C) # (D) << (A) break (B) while
(C) continue (D) operators
3. Which of the following shortcut is used to create
new Python Program? 8. Which operator is also called as Comparative
(A) Ctrl + C (B) Ctrl + F operator?
(C) Ctrl + B (D) Ctrl + N (A) Arithmetic (B) Relational
(C) Logical (D) Assignment
4. Which of the following character is used to give
comments in Python Program? 9. Which of the following is not logical operator?
(A) # (B) & (A) and (B) Or
(C) @ (D) $ (C) Not (D) Assignment

5. This symbol is used to print more than one item 10. Which operator is also called as Conditional
on a single line. operator?
(A) Semicolon(;) (B) Dollor($) (A) Ternary (B) Relational
(C) comma(,) (D) Colon(:) (C) Logical (D) Assignment

4
Chapter – 6
CONTROL STRUCTURES
1. How many important control structures are there 7. What is the output of the following snippet?
in Python? i=1
(A) 3 (B) 4 while True:
(C) 5 (D) 6 if i%3 ==0:
break
2. elif can be considered to be abbreviation of print(i,end='')
(A) nested if (B) if..else i +=1
(C) else if (D) if..elif (A) 12 (B) 123
(C) 1234 (D) 124
3. What plays a vital role in Python programming?
(A) Statements (B) Control 8. What is the output of the following snippet?
(C) Structure (D) Indentation T=1
while T:
4. Which statement is generally used as a print(True)
placeholder? break
(A) continue (B) break (A) False (B) True
(C) pass (D) goto (C) 0 (D) no output

5. The condition in the if statement should be in the 9. Which amongst is not a jump statement?
form of (A) for (B) goto
(A) Arithmetic or Relational expression (C) continue (D) break
(B) Arithmetic or Logical expression
(C) Relational or Logical expression 10. Which punctuation should be used in the block?
(D) Arithmetic if <condition>……..
statements-block 1
6. Which is the most comfortable loop? else:
(A) do..while (B) while statements-block 2
(C) for (D) if..elif (A) ; (B) :
(C) :: (D) !

Chapter – 7
PYTHON FUNCTIONS

1. A named blocks of code that are designed to do 3. Which function is called anonymous un-named
one specific job is called as function?
(A) Loop (B) Branching (A) Lambda (B) Recursion
(C) Function (D) Block (C) Function (D) define

2. A Function which calls itself is called as 4. Which of the following keyword is used to begin
(A) Built-in (B) Recursion the function block?
(C) Lambda (D) return (A) define (B) for
(C) finally (D) def

5
5. Which of the following keyword is used to exit a (II) Python keywords can be used as function
function block? name.
(A) define (B) return (A) I is correct and II is wrong
(C) finally (D) def (B) Both are correct
(C) I is wrong and II is correct
6. While defining a function which of the following (D) Both are wrong
symbol is used.
(A) ; (semicolon) (B) . (dot) 9. Pick the correct one to execute the given
(C) : (colon) (D) $ (dollar) statement successfully.
if ____ : print(x, " is a leap year")
7. In which arguments the correct positional order is (A) x%2=0 (B) x%4==0
passed to a function? (C) x/4=0 (D) x%4=0
(A) Required (B) Keyword
(C) Default (D) Variable-length 10. Which of the following keyword is used to
define the function testpython()?
8. Read the following statement and choose the (A) define (B) pass
correct statement(s). (C) def (D) while
(I) In Python, you don’t have to mention the specific
data types while defining function.

Chapter – 8
STRINGS AND STRING MANIPULATION
1. Which of the following is the output of the
following python code? 6. Which of the following is the slicing operator?
str1="TamilNadu" (A) { } (B) [ ] (C) < > (D) ( )
print(str1[::-1])
(A) Tamilnadu (B) Tmlau
(C) udanlimaT (D) udaNlimaT 7. What is stride?
(A) index value of slide operation
2. What will be the output of the following code? (B) first argument of slice operation
str1 = "Chennai Schools" (C) second argument of slice operation
str1[7] = "-" (D) third argument of slice operation
(A) Chennai-Schools (B) Chenna-School
(C) Type error (D) Chennai
8. Which of the following formatting character is
3. Which of the following operator is used for used to print exponential notation in upper case?
concatenation? (A) %e (B) %E (C) %g (D) %n
(A) + (B) & (C) * (D) =
9. Which of the following is used as placeholders or
4. Defining strings within triple quotes allows replacement fields which get replaced along with
creating: format( ) function?
(A) Single line Strings (B) Multiline Strings
(A) { } (B) < > (C) ++ (D) ^^
(C) Double line Strings (D) Multiple Strings

5. Strings in python: 10. The subscript of a string may be:


(A) Changeable (B) Mutable (A) Positive (B) Negative
(C) Immutable (D) flexible (C) Both (a) and (b) (D) Either (a) or (b)

6
Chapter – 9
LISTS, TUPLES, SETS AND DICTIONARY

1. Pick odd one in connection with collection data print(S)


type (A) [0,1,2,4,5] (B) [0,1,4,9,16]
(A) List (B) Tuple (C) [0,1,4,9,16,25] (D) [1,4,9,16,25]
(C) Dictionary (D) Loop
8. What is the use of type() function in python?
2. Let list1=[2,4,6,8,10], then print(List1[-2]) will (A) To create a Tuple
result in (B) To know the type of an element in tuple
(A) 10 (B) 8 (C) 4 (D) 6 (C) To know the data type of python object
(D) To create a list
3. Which of the following function is used to count
the number of elements in a list? 9. Which of the following statement is not correct?
(A) count( ) (B) find( ) (A) A list is mutable
(C)len( ) (D) index( ) (B) A tuple is immutable.
(C) The append() function is used to add an
4. If List=[10,20,30,40,50] then List[2]=35 will result element.
(A) [35,10,20,30,40,50] (B) [10,20,30,40,50,35] (D) The extend() function is used in tuple to add
(C) [10,20,35,40,50] (D) [10,35,30,40,50] elements in a list.

5. If List=[17,23,41,10] then List.append(32) will 10. Let setA={3,6,9}, setB={1,3,9}. What will be the
result result of the following snippet?
(A) [32,17,23,41,10] (B) [17,23,41,10,32] print(setA|setB)
(C) [10,17,23,32,41] (D) [41,32,23,17,10] (A) {3,6,9,1,3,9} (B) {3,9}
(C) {1} (D) {1,3,6,9}
6. Which of the following Python function can be
used to add more than one element within an 11. Which of the following set operation includes all
existing list? the elements that are in two sets but not the
(A) append( ) (B) append_more( ) one that are common to two sets?
(C) extend( ) (D) more( ) (A) Symmetric difference (B) Difference
(C) Intersection (D) Union
7. What will be the result of the following Python
code? 12. The keys in Python, dictionary is specified by
S=[x**2 for x in range(5)] (A) = (B) ; (C)+ (D) :

Chapter – 10
CLASSES AND OBJECTS
1. Which of the following are the key features of an 3. Class members are accessed through which
Object Oriented Programming language? operator?
(A) Constructor and Classes (A) & (B) . (C) # (D) %
(B) Constructor and Object
(C) Classes and Objects 4. Which of the following method is automatically
(D) Constructor and Destructor executed when an object is created?
(A) __object__( ) (B) __del__( )
2. Functions defined inside a class: (C) __func__( ) (D) __init__( )
(A) Functions (B) Module
(C) Methods (D) section 5. A private class variable is prefixed with
(A) __ (B) && (C) ## (D) **

7
6. Which of the following method is used as self.name=name
destructor? print(name)
(A) __init__( ) (B) __dest__( ) S=Student(“Tamil”)
(C) __rem__( ) (D) __del__( )
(A) Error (B) Tamil
(C) name (D) self
7. Which of the following class declaration is
correct?
9. Which of the following is the private class
(A) class class_name
variable?
(B) class class_name<>
(A) __num (B) ##num
(C) class class_name:
(C) $$num (D) &&num
(D) class class_name[ ]
10. The process of creating an object is called as:
8. Which of the following is the output of the
(A) Constructor (B) Destructor
following program?
(C) Initialize (D) Instantiation
class Student:
def __init__(self, name):

CHAPTER 11
DATABASE CONCEPTS

(A) one-to-one (B) one-to-many


1. What is the acronym of DBMS? (C) many-to-one (D) many-to-many
(A) DataBase Management Symbol
(B) Database Managing System 6. Who is called Father of Relational Database from
(C) DataBase Management System the following?
(D) DataBasic Management System (A) Chris Date (B)Hugh Darween
(C) Edgar Frank Codd (D) Edgar Frank Cadd
2. A table is known as
(A) tuple (B) attribute 7. Which of the following is an RDBMS?
(C) relation (D) entity (A) Dbase (B) Foxpro
(C) Microsoft Access (D) SQLite
3. Which database model represents parent-child
relationship? 8 What symbol is used for SELECT statement?
(A) Relational (B) Network (A) σ (B) Π (C) X (D) Ω
(C) Hierarchical (D) Object
9 A tuple is also known as
4. Relational database model was first proposed by (A) table (B) row
(A) E F Codd (B) E E Codd (C) attribute (D) field
(C) E F Cadd (D) E F Codder
10. Who developed ER model?
5. What type of relationship does hierarchical (A) Chen (B) EF Codd
model represents? (C) Chend (D) Chand

Chapter 12
STRUCTURED QUERY LANGUAGE

8
1. Which commands provide definitions for creating (C) Create, Reset, Update, Download
table structure, deleting relations, and modifying (D) Create, Read, Update, Delete
relation schemas?
(A) DDL (B) DML 9. Expand: DDL
(C) DCL (D) DQL (A) Data Definition Language
(B) Data Delivery Language
2. Which command lets to change the structure of (C) Data Defined Link
the table? (D) Data Delivery Link
(A) SELECT (B) ORDER BY
(C) MODIFY (D) ALTER 10. Expand: DML
(A) Data Maintenance Link
3. The command to delete a table is (B) Data Manipulation Link
(A) DROP (B) DELETE (C) Data Maintenance Language
(C) DELETE ALL (D) ALTER TABLE (D) Data Manipulation Language

4. Queries can be generated using 11. Expand: EDML


(A) SELECT (B) ORDER BY (A) Export Data Maintenance Link
(C) MODIFY (D) ALTER (B) Embedded Data Maintenance Link
(C) Embedded Data Manipulation Language
5. The clause used to sort data in a database (D) Export Data Manipulation Language
(A) SORT BY (B) ORDER BY
(C) GROUP BY (D) SELECT 12. Expand: DCL
(A) Data Connect Language
6. Expand: SQL (B) Data Connect Link
(A) Structured Query Language . (C) Data Control Link
(B) Structured Question Language (D) Data Control Language
(C) Sorted Query Language
(D) Sorted Question Language 13. Expand: TCL
(A) Transfer Connect Link
7. Expand: RDBMS (B) Transaction Connect Language
(A) Regional Data Base Maintenance System (C) Transaction Control Language
(B) Relational Data Base Maintenance System (D) Transfer Control Link
(C) Regional Data Base Management System
(D) Relational Data Base Management System 14. Expand: DQL
(A) Data Question Language
8. CRUD means (B) Data Query Language
(A) Create, Retrieved, Upload, Delete (C) Data Question Link
(B) Change, Read, Upload, Delete (D) Data Query Link

Chapter 13
PYTHON AND CSV FILES
1. A CSV file is also known as a
(A) Flat File (B) 3D File 3. Which of the following module is provided by
(C) String File (D) Random File Python to do several operations on the CSV
files?
2. The expansion of CRLF is (A) py (B) xls
(A) Control Return and Line Feed (C) csv (D) os
(B) Carriage Return and Form Feed
(C) Control Router and Line Feed
(D) Carriage Return and Line Feed

9
4. Which of the following mode is used when (D) chennai,mylapore
dealing with non-text files like image or exe mumbai,andheri
files?
(A) Text mode (B) Binary mode 8. Which of the following creates an object which
(C) xls mode (D) csv mode maps data to a dictionary?
(A) listreader( ) (B) reader( )
5. The command used to skip a row in a CSV file is (C) tuplereader( ) (D) DicReader( )
(A) next( ) (B) skip( )
(C) omit( ) (D) bounce( ) 9. Making some changes in the data of the existing
file or adding more data is called
6. Which of the following is a string used to (A) Editing (B) Appending
terminate lines produced by writer() method of (C) Modification (D) Alteration
csv module?
(A) Line Terminator (B) Enter key 10. What will be written inside the file test.csv using
(C) Form feed (D) Data Terminator the following program?
import csv
7. What is the output of the following program? D = [['Exam'],['Quarterly'],['Halfyearly']]
import csv csv.register_dialect('M',lineterminato
d=csv.reader(open('c:\......\......\city.csv')) r = '\n')
next(d) with open('c:\pyprg\ch13\line2.csv',
for row in d: 'w') as f:
print(row) wr = csv.writer(f,dialect='M')
wr.writerows(D)
if the file called “city.csv” contain the following f.close()
details (A) Exam Quarterly Halfyearly
chennai,mylapore (B) Exam Halfyearly Quarterly
mumbai,andheri (C) E
Q
(A) chennai,mylapore H
(B) mumbai,andheri (D) Exam,
Quarterly
(C) chennai Halfyearly
mumbai

CHAPTER 14
IMPORTING C++ PROGRAMS IN PYTHON

1. Which of the following is not a scripting (B) Application Programming Interface


language? (C) Application Performing Interface
(A) JavaScript (B) PHP (D) Application Programming Interlink
(C) Perl (D) HTML
4. A framework for interfacing Python and C++ is
2. Importing C++ program in a Python program is (A) Ctypes (B) SWIG
called (C) Cython (D) Boost
(A) wrapping (B) Downloading
(C) Interconnecting (D) Parsing 5. Which of the following is a software design
technique to split your code into separate
parts?
3. The expansion of API is (A) Object oriented Programming
(A) Application Programming Interpreter (B) Modular programming
(C) Low Level Programming

10
(D) Procedure oriented Programming if __name__ =='__main__':
main(sys.argv[1:])
6. The module which allows you to interface with (A) main(sys.argv[1:]) (B) __name__
the Windows operating system is (C) __main__ (D) argv
(A) OS module (B) sys module
(C) csv module (D) getopt module 9. Which of the following can be used for
processing text, numbers, images, and
7. getopt( ) will return an empty array if there is no scientific data?
error in splitting strings to (A) HTML (B) C
(A) argv variable (B) opt variable (C) C++ (D) PYTHON
(C) args variable (D) ifile variable
10. What does __name__ contains ?
8. Identify the function call statement in the (A) C++ filename (B) main( ) name
following snippet. (C) Python filename (D) OS module name

CHAPTER 15
DATA MANIPULATION THROUGH SQL

1. Which of the following is an organized collection


of data?
(A) Database (B) DBMS 6. Which of the following function retrieves the
(C) Information (D) Records average of a selected column of rows in a
table?
2. SQLite falls under which database system? (A) Add() (B) SUM()
(A) Flat file database system (C) AVG() (D) AVERAGE()
(B) Relational Database system
(C) Hierarchical database system 7. The function that returns the largest value of the
(D) Object oriented Database system selected column is
(A) MAX() (B) LARGE()
3. Which of the following is a control structure used (C) HIGH() (D) MAXIMUM()
to traverse and fetch the records of the
database? 8. Which of the following is called the master table?
(A) Pointer (B) Key (A) sqlite_master (B) sql_master
(C) Cursor (D) Insertion point (C) main_master (D) master_main

4. Any changes made in the values of the record 9. The most commonly used statement in SQL is
should be saved by the command (A) cursor (B) select
(A) Save (B) Save As (C) execute (D) commit
(C) Commit (D) Oblige
10. Which of the following clause avoid the
5. Which of the following executes the SQL duplicate?
command to perform some action? (A) Distinct (B) Remove
(A) Execute() (B) Key() (C) Where (D) GroupBy
(C) Cursor() (D) run()

Chapter 16
DATA VISUALIZATION USING PYPLOT:
LINE CHART, PIE CHART AND BAR CHART

11
1. Which is a python package used for 2D
graphics? 4. Read the following code: Identify the purpose of
(A) matplotlib.pyplot (B) matplotlib.pip this code and choose the right option from the
(C) matplotlib.numpy (D) matplotlib.plt following.
C:\Users\Your
2. Identify the package manager for Python Name\AppData\Local\Programs\Python\Pyt
packages, or modules. hon36-32\Scripts>pip list
(A) Matplotlib (B) PIP (A) List installed packages (B) list command
(C) plt.show( ) (D) python package (C) Install PIP (D) packages installed

3. Read the following code: Identify the purpose of 5. To install matplotlib, the following function will be
this code and choose the right option from the typed in your command prompt.
following. What does “-U”represents?
C:\Users\YourName\AppData\Local\Progra Python –m pip install –U pip
ms\Python\Python36-32\Scripts>pip – (A) downloading pip to the latest version
version (B) upgrading pip to the latest version
(A) Check if PIP is Installed (B) Install PIP (C) removing pip
(C) Download a Package (D) upgrading matplotlib to the latest version
(D) Check PIP version

6. Observe the output figure. Identify the coding for obtaining this output.

(A) import matplotlib.pyplot as plt (C) import matplotlib.pyplot as plt


plt.plot([1,2,3],[4,5,1]) plt.plot([2,3],[5,1])
plt.show() plt.show()

(B) import matplotlib.pyplot as plt (D) import matplotlib.pyplot as plt


plt.plot([1,2],[4,5]) plt.plot([1,3],[4,1])
plt.show() plt.show()

7. Read the code:


import matplotlib.pyplot as plt
plt.plot(3,2)

12
plt.show()
Identify the output for the above coding.
(A) (B)

(C) (D)

8. Which key is used to run the module?


(A) F6 (B) F4 10. Read the statements given below. Identify the
(C) F3 (D) F5 right option from the following for pie chart.
Statement A: To make a pie chart with Matplotlib,
9. Identify the right type of chart using the following we can use the plt.pie() function.
hints. Statement B: The autopct parameter allows us to
Hint 1: This chart is often used to visualize a trend display the percentage value using the Python
in data over intervals of time. string formatting.
Hint 2: The line in this type of chart is often drawn (A) Statement A is correct
chronologically. (B) Statement B is correct
(A) Line chart (B) Bar chart (C) Both the statements are correct
(C) Pie chart (D) Scatter plot (D) Both the statements are wrong

***************
PART – II
(2 MARKS)
ANSWER THE FOLLOWING QUESTIONS
1. What is a subroutine?
• Subroutines are the basic building blocks of 2. Define Function with respect to Programming
computer programs. language.
• Subroutines are small sections of code that • A function is a unit of code that is oft en
are used to perform a particular task that defined within a greater code structure.
can be used repeatedly.

13
3. Write the inference you get from X:=(78). 9. What is abstract data type?
(X : int) • Abstract Data type (ADT) is a type (or class)
for objects whose behavior is defined by a
4. Differentiate interface and implementation. set of value and a set of operations.
Interface Implementation
Interface just defines what Implementation carries 10. Differentiate constructors and selectors.
an object can do, but out the instructions Constructor Selectors
won’t actually do it defined in the interface Constructors are Selectors are
functions that build functions that retrieve
5. Which of the following is a normal function the abstract data information from the
definition and which is recursive function type. data type.
definition?
i) let rec sum x y: 11. What is a Pair? Give an example.
return x + y • Any way of bundling two values together
ii) let disp : into one can be considered as a pair.
print ‘welcome’ • Example:
iii) let rec sum num: lst[(0, 10), (1, 20)]
if (num!=0) then return num + sum (num-1)
else 12. What is a List? Give an example.
return num • List is constructed by placing expressions
Answer: within square brackets separated by
(i) Recursive function commas.
(ii) Normal function • Example: lst := [10, 20]
(iii) Recursive function
13. What is a Tuple? Give an example.
• A tuple is a comma-separated sequence of
6. What is subroutine? values surrounded with parentheses.
• Subroutines are the basic building blocks of
computer programs. 14. What is ADT?
• Subroutines are small sections of code that • ADT - Abstract Data type is a type (or class)
are used to perform a particular task that for objects whose behavior is defined by a
can be used repeatedly. set of value and a set of operations.
• In Programming languages these 15. What is wishful thinking?
subroutines are called as Functions. • Wishful Thinking is the formation of beliefs
7. What is pure function? and making decisions according to what
• Pure functions are functions which will give might be pleasing to imagine instead of by
exact result when the same arguments are appealing to reality.
passed.
16. What is a scope?
8. What is impure function? • Scope refers to the visibility of variables,
parameters and functions in one part of a
• The variables used inside the function may program to another part of the same
cause side effects though the functions program.
which are not passed with any arguments.
• In such cases the function is called impure 17. Why scope should be used for variable?
function. State the reason.
• The changes inside the function can't affect
the variable on the outside of the function in
unexpected ways.

14
18. What is mapping? 26. Write short notes on Tokens.
• The process of binding a variable name with • Python breaks each logical line into a
an object is called mapping. sequence of elementary lexical components
known as Tokens.
19. What do you mean by Namespaces? • The normal token types are
• Namespaces are containers for mapping 1) Identifiers,
names of variables to objects. 2) Keywords,
3) Operators,
20. How Python represents the private and 4) Delimiters and
protected Access specifiers? 5) Literals.
• Python prescribes a convention of prefixing
the name of the variable/method with single 27. What are the different operators that can be
or double underscore to emulate the used in Python?
behavior of protected and private access 1) Arithmetic operators
specifiers. 2) Relational or Comparative operators
3) Logical operators
21. What is an Algorithm? 4) Assignment operators
• An algorithm is a finite set of instructions to 5) Conditional operator
accomplish a particular task.
• It is a step-by-step procedure for solving a 28. What is a literal? Explain the types of
given problem. literals?
• Literal is a raw data given in a variable or
22. Define Pseudo code. constant.
• It’s simply an implementation of an
algorithm in the form of annotations and Types of Literals:
informative text written in plain English. • Numeric Literals
• It has no syntax like any of the programming o Numeric Literals consists of digits
language and thus can’t be compiled or and are immutable (unchangeable).
interpreted by the computer. o Numeric literals can belong to 3
different numerical types Integer,
Float and Complex.
23. What is Sorting? • String Literals
• Arranging elements (values) in a sequential o In Python a string literal is a
order. sequence of characters surrounded
by quotes.
24. What is searching? Write its types. • Boolean Literals
• Finding a particular element (value) from a o A Boolean literal can have any of the
set is called as searching. two values: True or False.
• Types of searching: • Escape Sequences
o Linear Search o In Python strings, the backslash "\"
o Binary Search is a special character, also called the
"escape" character.
25. What are the different modes that can be
29. Write short notes on Exponent data?
used to test Python Program?
An Exponent data contains decimal digit part,
• Interactive Mode
decimal point, exponent part followed by one or
• Script Mode
more digits.
Example: 12.E04, 24.e04

15
30. List the control structures in Python. • It provides better modularity for your
• Sequential application.
• Alternative or Branching
• Iterative or Looping 38. What is meant by scope of variable?
Mention its types.
31. Write note on break statement. • Scope of variable refers to the part of the
• The break is a jump statement. program, where it is accessible, i.e., area
• The breakstatement terminates the loop where you can refer (use) it.
containing it. • Types of scopes:
o Local scope and Global scope.
32. Write the syntax of if..else statement
if <condition>: 39. Define global scope.
statements-block 1 A variable, with global scope can be used
else: anywhere in the program. It can be created by
statements-block 2 defining a variable outside the scope of any
function/block.
33. Define control structure.
40. What is base condition in recursive
A program statement that causes a jump of control function?
from one part of the program to another is called The condition that is applied in any recursive
control structure or control statement. function is known as base condition.

34. Write note on range() in loop 41. How to set the limit for recursive function?
• The range() generates a list of values Give an example.
starting from start till stop-1. • sys.setrecursionlimit (limit_value) is used to
• The syntax of range(): set the limit for recursive function.
range (start,stop,[step]) • Example:
start – refers to the initial value import sys
stop – refers to the final value sys.setrecursionlimit(3000)
step – refers to increment value, this is
optional part. 42. What is String?
35. What is function? • String is a data type in python, which is
• Functions are named blocks of code that used to handle array of characters.
are designed to do specific job. • String is a sequence of Unicode characters
• Functions are nothing but a group of related that may be a combination of letters,
statements that perform a specific task. numbers, or special symbols enclosed
within single, double or even triple quotes.
36. Write the different types of function.
1. User defined functions 43. Do you modify a string in Python?
2. Built in functions • No, in python, strings are immutable, it
3. Recursive functions means, once you define a string, it cannot
4. Lambda functions be changed during execution.

37. What are the main advantages of function? 44. How will you delete a string in Python?
• It avoids repetition and makes high degree • Python will not allow deleting a particular
of code reusing. character in a string.

16
• Whereas the entire string can be removed • Object is a collection of data and function
using del command. that act on those data.
• Class is a template for the object.
45. What will be the output of the following
python code? 54. What is instantiation?
str1 = “School” • The process of creating object is called as
print(str1*3) “Class Instantiation”.
Output:
SchoolSchoolSchool 55. What is the output of the following
program?
46. What is slicing? class Sample:
Slice is a substring of a main string. __num=10
def disp(self):
47. What is List in Python? print(self.__num)
• A list in Python is known as a “sequence S=Sample()
data type” like strings. S.disp()
• It is an ordered collection of values print(S.__num)
enclosed within square brackets [ ].

48. How will you access the list elements in Output:


reverse order? AttributeError: 'Sample' object has no
• A negative index can be used to access an attribute '__num'
element in reverse order.
56. How will you create constructor in Python?
49. What will be the value of x in following
• In Python, there is a special function called
python code?
“init” which act as a Constructor. It must
List1=[2,4,6[1,3,5]]
x=len(List1) begin and end with double underscore.
Answer: 4 • This constructor function can be defined
with or without arguments.
50. Differentiate del with remove( ) function of • General format of __init__ method
List. (Constructor function)
• The del statement is used to delete known def __init__(self, [args ……..]):
elements whereas <statements>
• The remove( ) function is used to delete
elements of a list if its index is unknown. 57. What is the purpose of Destructor?
• Destructor destroyed the objects were
51. Write the syntax of creating a Tuple with n
created during instantiation.
number of elements.
Tuple_Name = (E1, E2, E2 ……. En) • Used to clean up any resources used by it.

52. What is set in Python? 58. Mention few examples of a database.


• A Set is a mutable and an unordered • Foxpro,
collection of elements without duplicates. • Dbase,
• MS-Access,
53. What is class? • OpenOffice Base
• Class is the main building block in Python.

17
59. List some examples of RDBMS. apply only to individual apply to a group of
• SQL server, column. one or more
• Oracle, columns.
• mysql,
• MariaDB, 66. Which component of SQL lets insert values
• SQLite. in tables and which lets to create a table?
• Create Table – command used to create
60. What is data consistency? tables in SQL
• Data Consistency means that data values • Insert into – command used to insert values
are the same at all instances of a database in a table
• Example:
61. What is the difference between Hierarchical
and Network data model? Create table Student (regno integer(3),
Hierarchical data Network data model sname varchar(20), mark integer(2));
model Insert into Student values (regno, sname,
In hierarchical model, In a Network model, a mark) values (121, ‘Raj’, 56);
a child record has child may have many
only one parent node parent nodes. 67. What is the difference between SQL and
MySQL?
62. What is normalization?
• Normalization reduces data redundancy and • SQL is a language that helps to create and
improves data integrity operate relational databases.
• MySQL is a database management system.
63. Write a query that selects all students
whose age is less than 18 in order wise. 68. What is CSV File?
Select * from Students where age < 19 order by • A CSV file is a human readable text file
name; where each line has a number of fields,
separated by commas or some other
64. Differentiate Unique and Primary Key delimiter.
constraint. • A CSV file is a text file, so it can be created
Unique Primary Key and edited using any text editor.
Constraint Constraint
This constraint This constraint 69. Mention the two ways to read a CSV file
ensures that no declares a field as a using Python.
two rows have the Primary key which 1. Use the csv module’s reader function
same value in the helps to uniquely 2. Use the DictReader class.
specified columns. identify a record.
The UNIQUE The primary key does 70. Mention the default modes of the File.
constraint can be not allow NULL • Open a file for reading (r) is the default
applied only to values, therefore a mode.
fields that have field declared as
been declared as primary key must have 71. What is use of next() function?
NOT NULL. the NOT NULL • The next( ) function returns the next item
constraint. from iterator. It can also be used to skip a
row of the csv file.
65. Write the difference between table
constraint and column constraint?
72. How will you sort more than one column
Column Constraint Table Constraint from a csv file? Give an example statement.
Column constraint Table constraint

18
• The sorted( ) method sorts the elements of 80. What is the advantage of declaring a column
a given item in a specific order – Ascending as “INTEGER PRIMARY KEY”
or Descending. If a column of a table is declared to be an
INTEGER PRIMARY KEY, then whenever a NULL
• Example:
will be used as an input for this column, the NULL
sortedlist = sorted(data, key=operator.itemgetter will be automatically converted into an integer
(Col_number),reverse=True) which will one larger than the highest value so far
used in that column.
73. What is the theoretical difference between
Scripting language and other 81. Write the command to populate record in a
programming language? table. Give an example.
Programming Scripting language • To populate (add record) the table
language "INSERT" command is passed to SQLite.
Requires compilation Do not require the • Example:
step compilation step sql_command = """INSERT INTO Student
Requires Compiler Requires interpreter (Rollno, Sname, Grade, gender, Average,
birth_date)
74. Differentiate compiler and interpreter. VALUES (NULL, "Akshay", "B", "M","87.8",
Compiler Interpreter "2001-12-12");""" cursor.execute(sql_
Translate instructions Directly executes the command)
into effect machine instructions in the source
code. programming language. 82. Which method is used to fetch all rows from
the database table?
75. Write the expansion of (i) SWIG (ii) MinGW • The fetchall() method is used to fetch all
(i) SWIG - Simplified Wrapper Interface Generator- rows from the database table.
Both C and C++.
(ii) MinGW - Minimalist GNU for Windows. 83. Define: Data Visualization.
• Data Visualization is the graphical
76. What is the use of modules? representation of information and data.
• Using the module name we can access the
functions defined inside the module. 84. List the general types of data visualization.
• The dot (.) operator is used to access the • Charts
functions. • Tables
77. What is the use of CD command? Give an • Graphs
example. • Maps
• CD command is used to change current • Infographics
directory in command prompt. • Dashboards

85. List the types of Visualizations in Matplotlib.


78. Mention the users who uses the Database.
• Line plot
• Users of database can be human users,
• Scatter plot
other programs or applications.
• Histogram
79. Which method is used to connect a • Box plot
database? Give an example. • Bar chart and
• The connect( ) method is used to connect a • Pie chart
database.
• Example: 86. How will you install Matplotlib?
connection = sqlite3.connect • Install matplotlib using pip.
("Academy.db") • Pip is a management software for installing
python packages.

19
87. Write the difference between the following and 'y' coordinates.
functions: This means, 4 co-
plt.plot([1,2,3,4]), ordinates according to
plt. plot([1,2,3,4], [1,4,9,16]). these lists: (1,1), (2,4),
(3,9) and (4,16).
plt.plot([1,2,3,4]) plt. plot([1,2,3,4],
[1,4,9,16])
Hover the graph and see This .plot takes many
the coordinates in the parameters, but the
bottom right. first two here are 'x'

*****
PART - III
(3 MARKS)
ANSWER THE FOLLOWING QUESTIONS:

1. Mention the characteristics of Interface. The return value of the The return value of the
• The class template specifies the interfaces pure functions solely impure functions does
to enable an object to be created and depends on its not solely depend on its
operated properly. arguments passed. arguments passed.
• An object's attributes and behavior is if you call the pure if you call the impure
controlled by sending functions to the functions with the same functions with the same
object. set of arguments, you set of arguments, you
will always get the might get the different
2. Why strlen is called pure function? same return values. return values
• Pure functions are functions which will give They do not have any They have side effects
exact result when the same arguments are side effects.
passed. They do not modify the They may modify the
• The strlen is a pure function because the arguments which are arguments which are
function takes one variable as a parameter, passed to them passed to them
and accesses it to find its length.
• This function reads external memory but 5. What happens if you modify a variable
does not change it, and the value returned outside the function? Give an example.
derives from the external memory
• One of the most popular groups of side
accessed.
effects is modifying the variable outside of
function.
3. What is the side effect of impure function?
• For example
Give example.
let y: = 0
• A function has side effects when it has
(int) inc (int) x
observable interaction with the outside
y: = y + x;
world.
return (y)
• Example:
let y: = 0
(int) inc (int) x • In the above example the value of y get
y: = y + x; changed inside the function definition due to
return (y) which the result will change each time.
• The side effect of the inc( ) function is it is
4. Differentiate pure and impure function. changing the data of the external visible
Pure Function Impure Function variable ‘y’. As we can see some side

20
effects are quite easy to spot and some of • Example:
them may tricky. lst[0]
10
6. Differentiate Concrete data type and abstract lst[1]
data type. 20
Concrete data type Abstract data type
A concrete data type An abstract data type 10. Identify Which of the following are List,
is a data type whose the representation of a Tuple and class?
representation is data type is unknown. (a) arr [1, 2, 34]
known. (b) arr (1, 2, 34)
(c) student [rno, name, mark]
7. Which strategy is used for program (d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’)
designing? Define that Strategy. (e) x= [2, 5, 6.5, [5, 6], 8.2]
• The 'wishful thinking' strategy is used for (f) employee [eno, ename, esal, eaddress]
designing programs. Answer:
(a) arr [1, 2, 34] List
• Wishful Thinking is the formation of beliefs
and making decisions according to what (b) arr (1, 2, 34) Tuple
might be pleasing to imagine instead of by (c) student [rno, name, mark] List
appealing to reality. (d) day= (‘sun’, ‘mon’, ‘tue’, ‘wed’) Tuple
(e) x= [2, 5, 6.5, [5, 6], 8.2] Class
8. Identify which of the following are (f) employee [eno, ename, esal, List
constructors and selectors? eaddress]
(a) N1=number() (b) accetnum(n1)
(c) displaynum(n1) (d) eval(a/b) 11. Define Local scope with an example.
(e) x,y= makeslope(m), makeslope(n) • Local scope refers to variables defined in
(f) display() current function.
• Always, a function will first look up for a
Answer: variable name in its local scope.
(a) N1=number() Constructor • Example:
(b) accetnum(n1) Selector 1. Disp():
(c) displaynum(n1) Selector 2. a:=7
(d) eval(a/b) Selector 3. print a
(e) x,y= makeslope Constructor 4. Disp()
(f) display() Constructor
12. Define Global scope with an example.
9. What are the different ways to access the • A variable which is declared outside of all
elements of a list. Give example. the functions in a program is known as
• The elements of a list can be accessed in global variable.
two ways. • This means, global variable can be
• The first way is via familiar method of accessed inside or outside of all the
multiple assignment, which unpacks a list functions in a program.
into its elements and binds each element to • Example
a different name. 1. a:=10
• Example: 2. Disp():
lst := [10, 20] 3. a:=7
x, y := lst 4. print a
• A second method for accessing the 5. Disp()
elements in a list is by the element selection 6. print a
operator, also expressed using square
brackets.

21
13. Define Enclosed scope with an example. • Definiteness
• A variable which is declared inside a function • Effectiveness
which contains another function definition with • Correctness
in it, the inner function can also access the • Simplicity
variable of the outer function. • Unambiguous
• When a compiler or interpreter search for a • Feasibility
variable in a program, it first search Local, • Portable
and then search Enclosing scopes. • Independent
• Example
1. Disp(): 17. Discuss about Algorithmic complexity and
2. a:=10 its types.
3. Disp1(): • The complexity of an algorithm f (n) gives
4. print a the running time and/or the storage space
5. Disp1() required by the algorithm in terms of n as
6. print a the size of input data.
7. Disp() • Time Complexity:
The Time complexity of an algorithm
14. Why access control is required? is given by the number of steps taken by the
• Access control is a security technique that algorithm to complete the process.
regulates who or what can view or use • Space Complexity:
resources in a computing environment. Space complexity of an algorithm is
• It is a fundamental concept in security that the amount of memory required to run to its
minimizes risk to the object. In other words completion.
access control is a selective restriction of
access to data. 18. What are the factors that influence time and
space complexity.
15. Identify the scope of the variables in the • Time Factor -Time is measured by counting
following pseudo code and write its output the number of key operations like
color:= Red comparisons in the sorting algorithm.
mycolor():
• Space Factor - Space is measured by the
b:=Blue
maximum memory space required by the
myfavcolor():
algorithm.
g:=Green
printcolor, b, g
myfavcolor()
19. Write a note on Asymptotic notation.
printcolor, b
Asymptotic Notations are languages that uses
mycolor()
meaningful statements about time and space
print color
complexity.
• Big O
Output:
Big O is often used to describe the
Blue Green
worst-case of an algorithm.
Blue
Blue Green • Big Ω
Blue Big Omega is the reverse Big O, if Bi
Red O is used to describe the upper
bound (worst - case) of a asymptotic
function, Big Omega is used to
16. List the characteristics of an algorithm.
describe the lower bound (best-
• Input case).
• Output
• Finiteness

22
• Big Θ
When an algorithm has a complexity ** (Exponent) >>> a ** 2 10000
with lower bound = upper bound,
>>> a//30
say that an algorithm has a
// (Floor Division) (Integer 3
complexity O (n log n) and Ω (n log
Division)
n), it’s actually has the complexity Θ
(n log n), which means the running
Example:
time of that algorithm always falls in
a=100
n log n in the best-case and worst-
b=10
case.
print ("The Sum = ",a+b)
print ("The Difference = ",a-b)
20. What do you understand by Dynamic
print ("The Product = ",a*b)
programming?
print ("The Quotient = ",a/b)
• Dynamic programming is an algorithmic
print ("The Remainder = ",a%30)
design method that can be used when the
print ("The Exponent = ",a**2)
solution to a problem can be viewed as the
print ("The Floor Division =",a//30)
result of a sequence of decisions.
• Dynamic programming approach is similar Output:
to divide and conquer. The Sum = 110
• The given problem is divided into smaller The Difference = 90
and yet smaller possible sub-problems. The Product = 1000
Dynamic programming is used whenever problems The Quotient = 10.0
can be divided into similar sub-problems. So that The Remainder = 10
their results can be re-used to complete the The Exponent = 10000
process. The Floor Division = 3

21. Write short notes on Arithmetic operator 22. What are the assignment operators that can
with examples. be used in Python?
An arithmetic operator is a mathematical operator • In Python, = is a simple assignment
that takes two operands and performs a calculation operator to assign values to variable.
on them. They are used for simple arithmetic. • Let a = 5 and b = 10 assigns the value 5 to
a and 10 to b these two-assignment
statement can also be given as a, b=5, 10
that assigns the value 5 and 10 on the right
Operator - to the variables a and b respectively.
Operation
Examples Result • There are various compound operators in
Assume a=100 and b=10. Evaluate the Python like +=, -=, *=, /=, %=, **= and //=
following expressions are also available.
Oper Example
Description
+ (Addition) >>> a + b 110 ator (Assume: x=10)
Assigns right side
>>> x=10
- (Subtraction) >>>a – b 90 = operands to left
>>> b=”Computer”
variable
* (Multiplication) >>> a*b 1000 Added and assign
>>> x+=20
+= back the result
/ (Division) >>> a / b 10.0 # x=x+20
to left operand
% (Modulus) >>> a % 30 10 Subtracted and
>>> x-=5
-= assign back the
# x=x-5
result to left operand

23
Multiplied and • In Python strings, the backslash "\" is a
>>> x*=5
*= assign back the special character, also called the "escape"
# x=x*5
result to left operand character.
Divided and assign • It is used in representing certain whitespace
>>> x/=2 characters:
/= back the
# x=x/2 "\t" is a tab, "\n" is a newline, and "\r"
result to left operand
Taken is a carriage return.
modulus(Remainder • For example to print the message "It's
) using two >>> x%=3 raining", the Python command is
%= >>> print ("It\'s raining")
operands and # x=x%3
assign the result It's raining
to left operand
Performed Escape
exponential (power) sequence Example Output
calculation on >>> x**=2 character
**=
operators and # x=x**2
\\ Backslash >>> print("\\test") \test
assign value to the
left operand Single- >>>
Performed floor \’ Doesn't
quote print("Doesn\'t")
division on operators
//= >>> x//=3 >>>
and assign value to Double-
\” print("\"Python\"" "Python"
the left operand quote
)
23. Explain Ternary operator with examples. print("Python","\n
\n New line Python Lang..
• Ternary operator is also known as ","Lang..")
conditional operator that evaluates print("Python","\t
\t Tab Python Lang..
something based on a condition being true ","Lang..")
or false.
• It simply allows testing a condition in a 25. What are string literals? Explain.
single line replacing the multiline if-else • In Python a string literal is a sequence of
making the code compact. characters surrounded by quotes.
• Python supports single, double and triple
The Syntax: quotes for a string.
Variable Name = [on_true] if [Test • A character literal is a single character
expression] else [on_false] surrounded by single or double quotes.
• The value with triple-quote "' '" is used to
Example: give multiline string literal.
min= 50 if 49 < 50 else 70
min= 50 if 49 > 50 else 70
Example Program:
Example Program: strings = "This is Python"
a, b = 30, 20 char = "C"
min = a if a < b else b multiline_str = "'This is a multiline string with
print ("The Minimum of A and B is ",min) more than one line code."'
print (strings)
Output: print (char)
The Minimum of A and B is 20 print (multiline_str)
24. Write short notes on Escape sequences with
examples.

24
Output: • if..else statement thus provides two
This is Python possibilities and the condition determines
C which BLOCK is to be executed.
This is a multiline string with more than one
line code.
28.. Using if..else..elif statement write a suitable
program to display largest of 3 numbers.
26. Write a program to display
Program:
A
num1=int(input("Enter number 1: "))
AB
num2=int(input("Enter number 2: "))
ABC
num3=int(input("Enter number 3: "))
ABCD
if (num1 > num2):
ABCDE
large=num1
elif (num2 > num3):
Program:
large=num2
for i in range (65, 70):
else:
for j in range (65, i+1): large=num3
print(chr(j), end=' ') print("The Largest number is: ",large)
print("")
Output:
Output: Enter number 1: 78
A Enter number 2: 90
AB Enter number 3: 34
ABC The Largest number is: 90
ABCD
ABCDE 29.. Write the syntax of while loop.
while <condition>:
27.. Write note on if..else structure. statements block 1
• The if .. else statement provides control to [else:
check the true block as well as the false block. statements block2]
• Syntax:
if <condition>: 30.. List the differences between break and
statements-block 1 continue statements.
else:
Break Continue
statements-block 2
Itis used terminates It is used to skip the
• Flow chart: the loop containing it. remaining part of a loop
Control of the and start with next
program flows to the iteration
statement
immediately after the
body of the loop

31.
1. Write the rules of local variable.
1. A variable with local scope can be accessed
only within the function/block that it is
created in.

25
2. When a variable is created inside the
function/block, the variable becomes local to Output:
it. Enter a year : 2001
3. A local variable only exists while the 2001 is not a Leap year
function is executing. Output:
4. The format arguments are also local to Enter a year : 2008
function. 2008 is a Leap year

32. Write the basic rules for global keyword in 36. What is composition in functions?
python. The value returned by a function may be used as
1. When we define a variable outside a an argument for another function in a nested
function, it’s global by default. You don’t manner. This is called composition.
have to use global keyword.
2. We use global keyword to read and write a
37. How recursive function works?
global variable inside a function.
1) Recursive function is called by some
3. Use of global keyword outside a function
external code.
has no effect
2) If the base condition is met then the
program gives meaningful output and exits.
33. What happens when we modify global
3) Otherwise, function does some required
variable inside the function?
processing and then calls itself to continue
• Without using the global keyword we cannot recursion.
modify the global variable inside the
function but we can only access the global 38. What are the points to be noted while
variable. defining a function?
• Function blocks begin with the keyword
34. Differentiate ceil( ) and floor( ) function?
“def” followed by function name and
ceil( ) floor( ) parenthesis ().
Returns the smallest Returns the largest • Any input parameters or arguments should
integer greater than or integer less than or equal be placed within these parentheses when
equal to the given to the given value.
define a function.
number
• The code block always comes after a colon
(:) and is indented.
General format: General format:
• The statement “return [expression]” exits
math.ceil(x) math.floor(x)
a function, optionally passing back an
Example: Example: expression to the caller.
import math import math • A “return” with no arguments is the same
x=26.7 x=26.7 as return None.
print(math.ceil(x)) print(math.floor(x))
39. Write a Python program to display the given
35. Write a Python code to check whether a pattern
given year is leap year or not. COMPUTER
def leap(year): COMPUTE
if((year%4==0 and year%100!=0) or
COMPUT
(year%400==0)):
print(year, " is a Leap year") COMPU
else: COMP
print(year, " is not a Leap year") COM
CO
y=int(input("Enter a year : ")) C
leap(y)

26
Coding: • Example:
str1="COMPUTER" num1=int (input("Number 1: "))
index=len(str1) num2=int (input("Number 2: "))
for i in str1: print ("The sum of { } and { } is {
print(str1[0:index]) }".format(num1, num2,(num1+num2)))
index-=1
Output:
40. Write a short about the followings with Number 1: 34
suitable example: Number 2: 54
(a) capitalize( ) The sum of 34 and 54 is 88
(b) swapcase( )
43. Write a note about count( ) function in
(a) capitalize( ) python.
• Used to capitalize the first character of the • Returns the number of substrings occurs
string. within the given range.
Example: • Remember that substring may be a single
>>> city="chennai" character.
>>> print(city.capitalize()) • Range (beg and end) arguments are
Chennai optional. If it is not given, python searched
(b) swapcase( ) in whole string. Search is case sensitive.
• This function will change case of every • General format of count( ):
character to its opposite case vice-versa. count(str, beg, end)
• Example:
Example: >>> str1="Raja Raja Chozhan"
>>> str1="tAmiL NaDu" >>> print(str1.count('Raja'))
>>> print(str1.swapcase()) 2
TaMIl nAdU >>> print(str1.count('r'))
0
>>> print(str1.count('R'))
41. What will be the output of the given python 2
program?
str1 = "welcome" 44. What are the advantages of Tuples over a
str2 = "to school" list?
str3=str1[:2]+str2[len(str2)-2:] 1. The elements of a list are changeable
print(str3) (mutable) whereas the elements of a tuple
Output: are unchangeable (immutable), this is the
key difference between tuples and list.
weol
2. The elements of a list are enclosed within
square brackets. But, the elements of a
42. What is the use of format( )? Give an tuple are enclosed by paranthesis.
example. 3. Iterating tuples is faster than list.
• The format( ) function used with strings is
very versatile and powerful function used for 45. Write a shot note about sort( ).
formatting strings. • The sort( ) is used to sorts the elements in a
list.
• The curly braces { } are used as
• The sorting process affects the original list.
placeholders or replacement fields which
• The general format:
get replaced along with format( ) function.

27
List.sort(reverse=True|False, 48. What are the difference between List and
key=myFunc) Dictionary?
• Both, reverse and key arguments are (1) List is an ordered set of elements. But, a
optional dictionary is a data structure that is used for
o If reverse is set to True, the list will matching one element (Key) with another
be sorted in descending order (Value).
o Ascending is default. (2) The index values can be used to access a
• Example: particular element. But, in dictionary key
MyList=['B','G','Z','A','V'] represents index. Remember that, key may
MyList.sort() be a number of a string.
print(MyList) (3) Lists are used to look up a value whereas a
• Output: dictionary is used to take one value and
['A', 'B', 'G', 'V', 'Z'] look up another value.

46. What will be the output of the following 50. What are class members? How do you
code? define it?
list = [2**x for x in range(5)] • Variables defined inside a class are called
print(list) as “Class Variable” and functions are
Output:
called as “Methods”.
[1, 2, 4, 8, 16]
• Class variable and methods are together
47. Explain the difference between del and known as members of the class.
clear( ) in dictionary with an example. • The class members should be accessed
• In Python dictionary, del keyword is used to through objects or instance of class.
delete a particular element.
• The clear( ) function is used to delete all the 51. Write a class with two private class
elements in a dictionary. variables and print the sum using a method.
• To remove the dictionary, you can use del class Add:
keyword with dictionary name.
def __init__(self, num1, num2):
• Example:
print("Constructor...")
Dict = {'Roll' : 12001, 'SName' :
'Meena', 'Mark1' : 98, 'Marl2' : 86} self.__num1=num1
del Dict['Mark1'] self.__num2=num2
Dict.clear()
del Dict def sum(self):
s=self.__num1 + self.__num2
48. List out the set operations supported by print("The sum=",s)
python.
Res=Add(32,65)
1. Union: It includes all elements from two or
more sets Res.sum()
2. Intersection: It includes the common
elements in two sets Output:
3. Difference: It includes all elements that are Constructor...
in fi rst set (say set A) but not in the second The sum= 97
set (say set B)
4. Symmetric difference: It includes all the
elements that are in two sets (say sets A 52. Find the error in the following program to
and B) but not the one that are common to get the given output?
two sets. class Fruits:
def __init__(self, f1, f2):

28
self.f1=f1 55. What is the difference between Select and
self.f2=f2 Project command?
Select Project
def display(self): Symbol: σ Symbol: π
The projection
print("Fruit 1 = %s, Fruit 2 = %s" The SELECT
eliminates all
%(self.f1, self.f2)) operation is used for
attributes of the input
selecting a subset with
relation but those
tuples according to a
F = Fruits ('Apple', 'Mango') mentioned in the
given condition.
del F.display projection list.
F.display()
56. What is the role of DBA?
Output: • Database Administrator or DBA is the one
who manages the complete database
Fruit 1 = Apple, Fruit 2 = Mango management system.
Error: • DBA takes care of the security of the
del F.display DBMS, managing the license keys,
This statement deletes the object F, Hence managing user accounts and access etc.
the Python shows attribute error.

Correct Statement: 57. Explain Cartesian Product with a suitable


example.
F.display
• Cross product is a way of combining two
relations. The resulting relation contains,
53. What is the output of the following both relations being combined.
program? • A x B means A times B, where the relation
class Greeting: A and B have different attributes.
def __init__(self, name): • This type of operation is helpful to merge
self.__name = name columns from two relations.

def display(self):
print("Good Morning ", self.__name)

obj=Greeting('Bindu Madhavan')
obj.display()

Output:
Good Morning Bindu Madhavan

54. How do define constructor and destructor in 58. Explain Object Model with example.
Python? • Object model stores the data in the form of
objects, attributes and methods, classes
• In Python, the constructors should be and Inheritance.
defined using __init__ special function. • This model handles more complex
• Destructors defined using __del__ special applications, such as Geographic
function. information System (GIS), scientific
experiments, engineering design and
manufacturing.

29
• It is used in file Management System. • Constraint is a condition applicable on a
• It represents real world objects, attributes field or set of fields.
and behaviors.
• It provides a clear modular structure. Primary Constraint:
• It is easy to maintain and modify the existing • The constraint declares a field as a Primary
code. key which helps to uniquely identify a
• An example of the Object model is Shape, record.
Circle, Rectangle and Triangle are all • The primary key does not allow NULL
objects in this model. values and therefore a field declared as
• Circle has the attribute radius. primary key must have the NOT NULL
• Rectangle has the attributes length constraint.
and breadth.
• Triangle has the attributes base and 61. Write a SQL statement to modify the student
height. table structure by adding a new field.
• The objects Circle, Rectangle and ALTER TABLE student ADD (field1 integer(3),
Triangle inherit from the object field2 integer(3));
Shape.
62. Write any three DDL commands. / Write a
59. Write a note on different types of DBMS short note on (i) Alter (ii) Truncate (iii) Drop.
users. (i) Alter:
• Database Administrators: • The alter command is used to alter the table
Database Administrator or DBA is the one structure like adding a column, renaming
who manages the complete database the existing column, change the data type of
management system. DBA takes care of the any column or size of the column or delete
security of the DBMS, managing the license the column from the table.
keys, managing user accounts and access • Syntax:
etc. ALTER TABLE <table-name> ADD
• Application Programmers or Software <column-name><data type><size>;
Developers:
This user group is involved in developing (ii) Truncate:
and designing the parts of DBMS. • The truncate command is used to delete all
the rows from the table, the structure
• End User: remains and the space is freed from the
All modern applications, web or mobile, table.
store user data. Applications are • Syntax:
programmed in such a way that they collect TRUNCATE TABLE table-name;
user data and store the data on DBMS
systems running on their server. End users (iii) Drop:
are the one who store, retrieve, update and • The drop command is used to remove a
delete data. table from the database.
• Database designers: • If you drop a table, all the rows in the table
Database designers are responsible for is deleted and the table structure is
identifying the data to be stored in the removed from the database.
database for choosing appropriate • When drop a table, it must be empty.
structures to represent and store the data. • Syntax:
DROP TABLE table-name;
60. What is a constraint? Write short note on
Primary key constraint.
Constraint:

30
63. Write the use of Save point command with [‘1’, ‘Madhu’, ‘18/12/2001’],
an example. [‘2’, ‘Sowmya’,’19/2/1998’],
• The SAVEPOINT command is used to [‘3’, ‘Sangeetha’,’20/3/1999’],
temporarily save a transaction so that you [‘4’, ‘Eshwar’, ‘21/4/2000’],
can rollback to the point whenever required. [‘5’, ‘Anand’, ‘22/5/2001’]]
• The different states of our table can be csv.register_dialect(‘myDialect’,delimiter = ‘|’)
saved at anytime using different names and with open(‘c:\pyprg\ch13\dob.csv’, ‘w’) as f:
the rollback to that state can be done using writer = csv.writer(f, dialect=’myDialect’)
the ROLLBACK command. for row in info:
• Syntax: writer.writerow(row)
SAVEPOINT savepoint_name; f.close()
• Example:
UPDATE Student SET Name = 68. What is the difference between the write
‘Mini’ WHERE Admno=105; mode and append mode?
SAVEPOINT A; Write mode (w) Append mode (a)
Open a file for writing. Open for appending at
64. Write a SQL statement using DISTINCT the end of the file without
keyword. truncating it.
SELECT DISTINCT Place FROM Student; Creates a new file if it Creates a new file if it
does not exist or does not exist
65. Write a note on open( ) function of python. truncates the file if it
What is the difference between the two exists
methods?
• Python has a built-in function open() to open
a file. 69. What is the difference between reader() and
• This function returns a file object, also DictReader() function?
called a handle, as it is used to read or reader( ) DictReader( )
modify the file accordingly. The reader function is DictReader works by
• For Example designed to take each reading the first line of the
f = open("sample.txt") line of the file and CSV and using each
f = open('c:\\pyprg\\ch13sample5.csv') make a list of all comma separated value
columns. in this line as a dictionary
66. Write a Python program to modify an key.
existing file.
import csv 70. Differentiate PYTHON and C++
row = ['3', 'Meena', 'Bangalore'] Python C++
with open('student.csv', 'r') as readFile: Python is typically an C++ is typically a
reader = csv.reader(readFile) "interpreted" language "compiled" language
lines = list(reader) C++ is compiled
lines[3] = row Python is a dynamic-
statically typed
with open('student.csv', 'w') as writeFile: typed language
language
writer = csv.writer(writeFile) Data type is required
writer.writerows(lines) Data type is not required
while declaring
readFile.close() while declaring variable
variable
writeFile.close() It can act both as
It is a general purpose
scripting and general
67. Write a Python program to read a CSV file language
purpose language
with default delimiter comma (,).
import csv
info = [[‘SNO’, ‘Person’, ‘DOB’],

31
71. What are the applications of scripting fetchone( ) fetchmany( )
language? The fetchone () method fetchmany()
• To automate certain tasks in a program returns the next row of method that
• Extracting information from a data set a query result set or returns the next
• Less code intensive as compared to None in case there is number of rows (n)
traditional programming language no row left. of the result set
• Can bring new functions to applications and
glue complex systems together 77. What is the use of Where Clause? Give a
python statement Using the where clause.
72. What is MinGW? What is its use? • The WHERE clause is used to extract only
• MinGW refers to a set of runtime header those records that fulfil a specified
files, used in compiling and linking the code condition.
of C, C++ and FORTRAN to be run on • Example:
Windows Operating System. import sqlite3
• MinGW allows to compile and execute C++ connection = sqlite3.connect("Academy.db")
program dynamically through Python cursor = connection.cursor()
program using g++. cursor.execute("SELECT DISTINCT
(Grade) FROM student where gender='M'")
73. Identify the module, operator, definition result = cursor.fetchall()
name for the following print(*result,sep="\n")
welcome.display( )
• Module : welcome 78. Read the following details. Based on that
• Operator : dot( . ) write a python script to display department
• Definition name : display( ) wise records
database name: organization.db
74. What is sys.argv? What does it contain? Table name: Employee
• sys.argv is the list of command-line Columns in the table: Eno, EmpName, Esal,
arguments passed to the Python program. Dept
• Argv contains all the items that come along
via the command-line input, it's basically an Answer:
array holding the command-line arguments import sqlite3
of the program. connection = sqlite3.connect("organization.db")
cursor = connection.cursor()
cursor.execute("SELECT Eno, EmpName,
75. What is SQLite? What is it advantage?
Esal, Dept FROM Employee Group BY Dept")
• SQLite is a simple relational database result = cursor.fetchall()
system, which saves its data in regular data print(*result,sep="\n")
files or even in the internal memory of the
computer. 79. Read the following details. Based on that
• Advantages: write a python script to display records in
1. It is designed to be embedded in descending order of Eno
applications, instead of using a separate database name: organization.db
database server program such as MySQLor Table name: Employee
Oracle. Columns in the table: Eno, EmpName, Esal,
2. SQLite is fast, rigorously tested, and Dept
flexible, making it easier to work. Python
has a native library for SQLite. Answer:
import sqlite3
76. Mention the difference between fetchone()
connection = sqlite3.connect("organisation.db")
and fetchmany()
cursor = connection.cursor()

32
cursor.execute("SELECT Eno, EmpName, Esal, b. To Check the version of PIP installed in your PC.
Dept FROM employee Order BY Eno") • Python –m pip install –U pip
result = cursor.fetchall()
c. To list the packages in matplotlib.
print(*result,sep="\n") • pip list

80. Draw the output for the following data


visualization plot. 83. Write the plot for the following pie chart
import matplotlib.pyplot as plt output.
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two",
color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show()

Solution:

Solution:
import matplotlib.pyplot as plt
labels = ["Sleeping", "Playing", "Working", "Eating"]
sizes = [292, 542, 83, 83]
colors = ['green', 'blue', 'red', 'violet']
explode=[0,0,0,0.1]
plt.pie (sizes, labels = labels, explode=explode,
colors=colors, autopct = '%1.1f%%', shadow=True,
startangle=140)
plt.axes().set_aspect ("equal")
plt.title ('Intersing Graph Check it out')
plt.show( )

81. Write any three uses of data visualization.


1. Data Visualization help users to analyze
and interpret the data easily.
2. It makes complex data understandable and
usable.
3. Various Charts in Data Visualization helps
to show relationship in the data for one or
more variables.

82. Write the coding for the following:


a. To check if PIP is Installed in your PC.
• pip --version

33
****
PART - IV
(5 MARKS)
ANSWER THE FOLLOWING QUESTIONS:
1. What are called Parameters and write a note • Pure functions are functions which will give
on exact result when the same arguments are
(i) Parameter without Type passed.
(ii) Parameter with Type • A function can be a pure function provided it
Parameters are the variables in a function definition should not have any external variable which
and arguments are the values which are passed to will alter the behavior of that variable.
a function definition. • Example:
let square x
(i) Parameter without Type return: x * x
• Example:
(requires: b>=0 ) • Advantages of pure function:
(returns: a to the power of b) If a function is pure, then if it is
let rec pow a b:= called several times with the same
if b=0 then 1 arguments, the compiler only needs to
else a * pow a (b-1) actually call the function once.

• In the above function definition variable ‘b’ is • The strlen is a pure function because the
the parameter and the value which is function takes one variable as a parameter,
passed to the variable ‘b’ is the argument. and accesses it to find its length. This
• The precondition (requires) and post function reads external memory but does
condition (returns) of the function is given. not change it, and the value returned
• Note we have not mentioned any types: derives from the external memory
(data types). Some language compiler accessed.
solves this type (data type) inference
problem algorithmically, but some require Impure functions:
the type to be mentioned. • The variables used inside the function may
cause side effects though the functions
(ii) Parameter with Type which are not passed with any arguments.
• Example: • In such cases the function is called impure
(requires: b> 0 ) function.
(returns: a to the power of b ) • When a function depends on variables or
let rec pow (a: int) (b: int) : int := functions outside of its definition block, you
if b=0 then 1 can never be sure that the function will
else a * pow b (a-1) behave the same every time it’s called.
• Example:
• When we write the type annotations for ‘a’ let Random number
and ‘b’ the parentheses are mandatory. let a := random()
• Generally we can leave out these if a > 10 then
annotations, because it's simpler to let the return: a
compiler infer them. else
return: 10
2. Explain Pure and impure functions with an
example. 3. What is a List? Why List can be called as
Pure functions: Pairs? Explain with suitable example
List:

34
• List is constructed by placing expressions • A variable which is declared inside a function
within square brackets separated by which contains another function definition with
commas. in it, the inner function can also access the
• List can store multiple values. Each value variable of the outer function.
can be of any type and can even be another • When a compiler or interpreter search for a
list. variable in a program, it first search Local,
and then search Enclosing scopes.
Pairs: • Example
• Any way of bundling two values together 1. Disp():
into one can be considered as a pair. Lists 2. a:=10
are a common method to do so. 3. Disp1():
• Therefore List can be called as Pairs. 4. print a
5. Disp1()
Example: 6. print a
rational(n, d): 7. Disp()
return [n, d]
numer(x): (iv) built-in scope:
return x[0] • The built-in scope has all the names that
denom(x): are pre-loaded into the program scope
return x[1] when we start the compiler or interpreter.
• Any variable or module which is defined in
4. Explain the types of scopes for variable or the library functions of a programming
LEGB rule with example. language has Built-in or module scope.
(i) Local scope: • They are loaded as soon as the library files
• Local scope refers to variables defined in are imported to the program.
current function.
• Always, a function will first look up for a 6. Write any Five Characteristics of Modules.
variable name in its local scope. 1. Modules contain instructions, processing
• Example: logic, and data.
1. Disp(): 2. Modules can be separately compiled and
2. a:=7 stored in a library.
3. print a 3. Modules can be included in a program.
4. Disp() 4. Module segments can be used by invoking
a name and some parameters.
(ii) Global scope: 5. Module segments can be used by other
• A variable which is declared outside of all modules.
the functions in a program is known as
global variable. 7. Write any five benefits in using modular
• This means, global variable can be programming.
accessed inside or outside of all the 1. Less code to be written.
functions in a program. 2. A single procedure can be developed for
• Example reuse, eliminating the need to retype the
1. a:=10 code many times.
2. Disp(): 3. Programs can be designed more easily
3. a:=7 because a small team deals with only a
4. print a small part of the entire code.
5. Disp() 4. Modular programming allows many
6. print a programmers to collaborate on the same
application.
(iii) Enclosed scope: 5. The code is stored across multiple files.

35
6. Code is short, simple and easy to • If the search element is greater
understand. than the number in the middle
7. Errors can easily be identified, as they are index, then select the elements
localized to a subroutine or function. to the right side of the middle
8. The same code can be used in many index, and go to Step-1.
applications. • If the search element is less than
9. The scoping of variables can easily be the number in the middle index,
controlled. then select the elements to the
left side of the middle index, and
8. Discuss about Linear search algorithm. start with Step-1.
• Linear search also called sequential search 2. When a match is found, display success
is a sequential method for finding a message with the index of the element
particular value in a list. matched.
• This method checks the search element 3. If no match is found for all comparisons,
with each element in sequence until the then display unsuccessful message.
desired element is found or the list is
exhausted. 10. Explain the Bubble sort algorithm with
• In this searching algorithm, list need not be example.
ordered. • Bubble sort is a simple sorting algorithm.
• Pseudo code: • The algorithm starts at the beginning of the
1. Traverse the array using for loop list of values stored in an array.
2. In every iteration, compare the target • It compares each pair of adjacent elements
search key value with the current value and swaps them if they are in the unsorted
of the list. order.
• If the values match, display the • This comparison and passed to be
current index and value of the continued until no swaps are needed, which
array indicates that the list of values stored in an
• If the values do not match, move array is sorted.
on to the next array element. • The algorithm is a comparison sort, is
3. If no match is found, display the search named for the way smaller elements
element not found. "bubble" to the top of the list.
• Although the algorithm is simple, it is too
9. What is Binary search? Discuss with slow and less efficient when compared to
example. insertion sort and other sorting methods.
• Binary search also called half-interval • Assume list is an array of n elements. The
search algorithm. It finds the position of a swap function swaps the values of the given
search element within a sorted array. array elements.
• The binary search algorithm can be done as • Pseudo code
divide-and-conquer search algorithm and 1. Start with the first element i.e., index = 0,
executes in logarithmic time. compare the current element with the next
• Pseudo code: element of the array.
1. Start with the middle element: 2. If the current element is greater than the
• If the search element is equal to next element of the array, swap them.
the middle element of the array 3. If the current element is less than the
i.e., the middle value = number next or right side of the element, move to
of elements in array/2, then the next element. Go to Step 1 and repeat
return the index of the middle until end of the index is reached.
element.
• If not, then compare the middle
element with the search value

36
11. Explain the concept of Dynamic • A script is a text file containing the Python
programming with suitable example. statements.
• Dynamic programming is an algorithmic • Python Scripts are reusable code.
design method that can be used when the • Once the script is created, it can be
solution to a problem can be viewed as the executed again and again without retyping.
result of a sequence of decisions. • The Scripts are editable.
• Dynamic programming approach is similar
to divide and conquer. (ii) Creating Scripts in Python:
• The given problem is divided into smaller 1. Choose File → New File or press Ctrl + N in
and yet smaller possible sub-problems. Python shell window.
• Dynamic programming is used whenever 2. An untitled blank script text editor will be
problems can be divided into similar sub- displayed on screen
problems. so that their results can be re- 3. Type the code in Script editor
used to complete the process.
• Dynamic programming approaches are (iii) Saving Python Script:
used to find the solution in optimized way. 1. Choose File → Save or Press Ctrl + S
• For every inner sub problem, dynamic 2. Now, Save As dialog box appears on the
algorithm will try to check the results of the screen.
previously solved sub-problems. 3. In the Save As dialog box, select the
• The solutions of overlapped sub-problems location where you want to save Python
are combined in order to get the better code, and type the file name in File Name
solution. box.
• Steps to do Dynamic programming 4. Python files are by default saved with
o The given problem will be divided extension .py.
into smaller overlapping sub- 5. Finally, click Save button to save Python
problems. script.
o An optimum solution for the given
problem can be achieved by using (iv) Executing Python Script:
result of smaller sub-problem. • Choose Run → Run Module or Press F5
o Dynamic algorithms uses
Memoization. 13. Explain input() and print() functions with
• Example: examples.
Fibonacci Iterative Algorithm with Dynamic • A program needs to interact with the user to
programming approach accomplish the desired task; this can be
Initialize f0=0, f1 =1 achieved using Input-Output functions.
step-1: Print the initial values of • The input() function helps to enter data at
Fibonacci f0 and f1
run time by the user
step-2: Calculate fibanocci fib ← f0 +
f1 • The output function print() is used to display
step-3: Assign f0← f1, f1← fib the result of the program on the screen after
step-4: Print the next consecutive execution.
value of fibanocci fib
step-5: Goto step-2 and repeat until The print() function
the specified number of
• In Python, the print() function is used to
terms generated
display result on the screen.
12. Describe in detail the procedure Script • The syntax:
mode programming. print(“string to be displayed as
(i) Script mode Programming: output ” )
print(variable )

37
print(“String to be displayed as Enter Your City: Madurai
output ”, variable) >>> print (“I am from “, city)
print(“String1 ”, variable, “String 2”, I am from Madurai
variable, “String 3” ……)
• The print( ) evaluates the expression before 14. Discuss in detail about Tokens in Python
printing it on the monitor. Python breaks each logical line into a sequence of
• The print( ) displays an entire statement elementary lexical components known as Tokens.
which is specified within print( ). 1) Identifiers,
2) Keywords,
• Comma ( , ) is used as a separator in print( )
3) Operators,
to print more than one item.
4) Delimiters and
• Example:
5) Literals.
>>> print (“Welcome to Python
Programming”) Whitespace separation is necessary between
Welcome to Python Programming tokens, identifiers or keywords.
>>> x = 5
>>> y = 6 (1) Identifiers
>>> z = x + y • An Identifier is a name used to identify a
>>> print (z) variable, function, class, module or object.
11
• An identifier must start with an alphabet
The input( ) function (A..Z or a..z) or underscore ( _ ).
• In Python, input( ) function is used to accept • Identifiers may contain digits (0 .. 9)
data as input at run time. • Python identifiers are case sensitive i.e.
• The syntax: uppercase and lowercase letters are
Variable = input (“prompt string”) distinct.
• Where, prompt string in the syntax is a • Identifiers must not be a python keyword.
statement or message to the user, to know • Python does not allow punctuation
what input can be given. character such as %,$, @ etc., within
• If a prompt string is used, it is displayed on identifiers.
the monitor; the user can provide expected • Examples:
data from the input device. Sum, total_marks, regno, num1
• The input( ) takes whatever is typed from
the keyboard and stores the entered data in (2) Keywords
the given variable. • Keywords are special words used by Python
• If prompt string is not given in input( ) no interpreter to recognize the structure of
message is displayed on the screen. program.
• The input ( ) accepts all data as string or • As these words have specific meaning for
characters but not as numbers. interpreter, they cannot be used for any
• If a numerical value is entered, the input other purpose.
values should be explicitly converted into • Example:
numeric data type. The int( ) function is and, del, global etc.,
used to convert string data as integer data
explicitly. (3) Operators
• Example: Operators are special symbols which represent
>>> city=input (“Enter Your City: ”) computations, conditional matching etc.

38
The value of an operator used is called operands.
Operators are categorized as (4) Delimiters
i. Arithmetic operators • Python uses the symbols and symbol
ii. Relational or Comparative operators combinations as delimiters in expressions,
iii. Logical operators lists, dictionaries and strings.
iv. Assignment operators
• Examples:
v. Conditional operator
( ), { }, [ ]
(i) Arithmetic operators
• An arithmetic operator is a mathematical (5) Literals
operator that takes two operands and • Literal is a raw data given in a variable or
performs a calculation on them. constant.
• Operators: • Types of Literals:
+, -, *, /, %, **, // i. Numeric
ii. String
(ii) Relational or Comparative operators iii. Boolean
• A Relational operator is also called as iv. Escape sequences
Comparative operator which checks the
relationship between two operands. (i) Numeric Literals
• If the relation is true, it returns True; • Numeric Literals consists of digits and are
otherwise it returns False. immutable (unchangeable).
• Operators: • Numeric literals can belong to 3 different
==, >, >=, <, <=, != numerical types Integer, Float and Complex.

(iii) Logical operators (ii) String Literals


• Logical operators are used to perform • String literal is a sequence of characters
logical operations on the given relational surrounded by quotes.
expressions. • Python supports single, double and triple
• Operators: quotes for a string.
and, or, not.
(iii) Boolean Literals
(iv) Assignment operators • A Boolean literal can have any of the two
• Assignment operator to assign values to values: True or False.
variable.
• Operators (iv) Escape Sequences
+=, -=, *=, /=, %=, **=, //= • In Python strings, the backslash "\" is a
special character, also called the "escape"
(v) Conditional operator character.
• Ternary operator is also known as • It is used in representing certain whitespace
conditional operator that evaluate based on characters: "\t" is a tab, "\n" is a newline,
a condition being true or false. and "\r" is a carriage return.
• The Syntax:
Variable Name = [on_true] if [Test 15. Write a detail note on for loop
expression] else [on_false] • The forloop is the most comfortable loop.
• It is also an entry check loop.

39
• The condition is checked in the beginning else:
and the body of the loopis executed if it is statements
statements-block n
only True otherwise the loop is not
executed. In the syntax of if..elif..else mentioned above,
• Syntax: condition-11 is tested if it is true thenstatements
thenstatements-
for counter_variable in sequence:
block1 is executed, otherwise the control checks
statements--block 1
[else: # optional block condition-2,
2, if it is true statementsblock2is executed
statements--block 2] and even if it fails statements
statements-block n mentioned in
else part is executed.
• Usually in Python, forloop uses the
range()function in the sequence to specify ‘elif’ clause combines if..else-if..else
if..else statements to
the initial, final and increment values. one if..elif…else. ‘elif’ can be considered to be
• The range()generates a list of values abbreviation of ‘else if’. In an ‘if’ statement there is
starting from starttill stop-1. no limitt of ‘elif’ clause that can be used, but an
• The syntax of range():
‘else’ clause if used should be placed at the end.
range (start,stop,[step])
1. start – refers to the initial value
2. stop – refers to the final value Flowchart:
3. step – refers to increment value, this
is optional part.
• Flowchart

• Example:
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd
nEnd of the loop")
Output: Example:
2468 m1=int (input(“Enter mark in first subject : ”))
End of the loop m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
16.. Write a detail note on if..else..elif statement if avg>=80:
with suitable example. print (“Grade : A”)
Syntax: elifavg>=70 and avg<80:
if <condition-1>: print (“Grade : B”)
statements-block 1
elif<condition-2>: elifavg>=60 and avg<70:
statements-block 2 print (“Grade : C”)

40
elifavg>=50 and avg<60: def leap(year):
print (“Grade : D”) if((year%4==0 and year%100!=0) or
else: (year%400==0)):
print(year, " is a Leap year")
print (“Grade : E”)
else:
print(year, " is not a Leap year")
Output:
Enter mark in first subject : 34 y=int(input("Enter a year : "))
Enter mark in second subject : 78 leap(y)
Grade : D
(II) Built-in Functions:
17. Write a program to display all 3 digit odd The functions which are available with
numbers. Python by default is known as built-in functions.

18. Explain the different types of function with (III) Lambda functions
an example. • In Python, anonymous function is a function
In Python, the functions are classified as different that is defined without a name.
types. • While normal functions are defined using
I. User defined functions
the def keyword, in Python anonymous
II. Built-in functions
functions are defined using the lambda
III. Lambda functions
keyword.
IV. Recursive functions
• Hence, anonymous functions are also called
as lambda functions.
(I) User defined functions:
When defining functions there are multiple things
Use of lambda or anonymous function:
that need to be noted:
• Lambda function is mostly used for creating
• Function blocks begin with the keyword small and one-time anonymous function.
“def” followed by function name and • Lambda functions are mainly used in
parenthesis (). combination with the functions like filter(),
• Any input parameters or arguments should map() and reduce().
be placed within these parentheses when
define a function. Syntax of lambda function:
• The code block always comes after a colon
lambda [argument(s)]: expression
(:) and is indented.
• The statement “return [expression]” exits
a function, optionally passing back an Example:
expression to the caller. sqr=lambda x:x**2
• A “return” with no arguments is the same num=int(input("Enter a number: "))
as return None. print("The sequre of ",num, " is ", sqr(num))

syntax of creating a user defined function: (IV) Recursive functions


def <function_name( [parameter1, • When a function calls itself is known as
parameter2……])>: recursion.
<block of statements> • Recursion works like loop but sometimes it
Return <expression/None> makes more sense to use recursion than
loop.
Example:

41
• The condition that is applied in any
recursive function is known as base Example:
condition. def loc():
• A base condition is must in every recursive y=0
function otherwise it will continue to execute print(y)
like an infinite loop. loc()

Working of recursive function: (II) Global Scope:


1. Recursive function is called by some external • Defining a variable outside the scope of any
code. function/block.
2. If the base condition is met then the program • Global scope can be used anywhere in the
gives meaningful output and exits. program.
3. Otherwise, function does some required
processing and then calls itself to continue Basic rules for global keyword in python:
recursion. • When we define a variable outside a
function, it’s global by default. You don’t
Example: have to use global keyword.
def fact(n): • We use global keyword to read and write a
if n == 0: global variable inside a function.
return 1 • Use of global keyword outside a function
else: has no effect
return n * fact (n-1)
print (fact (0)) Example:
print (fact (5)) c=1
def add():
print(c)
19. Explain the scope of variables with an add()
example.
• Scope of variable refers to the part of the 20. Explain the following built-in functions.
program, where it is accessible, i.e., area (a) id()
(b) chr()
where you can refer (use) it.
(c) round()
• Types of scopes: (d) type()
o Local scope and Global scope. (e) pow()
(I) Local Scope: (a) id( )
• A variable declared inside the function's • Returns the “identity of an object” ie. the
body or in the local scope is known as local memory address of the object.
variable. • Example:
X=15
Rules of local variable: print("Address of X is: ",id(X))
• A variable with local scope can be accessed Output:
only within the function/block that it is Address of X is: 264398144
created in.
• When a variable is created inside the (b) chr( )
function/block, the variable becomes local to • Returns the Unicode character for the given
it. ASCII value.
• A local variable only exists while the • Example:
function is executing. Ch=65
• The format arguments are also local to print(“Unicode character of ”, Ch, “is:
function. ”, chr(Ch))

42
Output: • When a function calls itself is known as
Unicode character of 65 is : A recursion.
• Recursion works like loop but sometimes it
(c) round( ) makes more sense to use recursion than
• Returns the nearest integer to its input. loop.
• General format:
• The condition that is applied in any
round(number [,ndigits])
recursive function is known as base
condition.
1) number argument is used to specify
the value to be rounded. • A base condition is must in every recursive
2) ndigits argument is used to specify function otherwise it will continue to execute
the number of decimal digits desired like an infinite loop.
after rounding.
Working of recursive function:
• Example:
• Recursive function is called by some
x=17.9
y=22.81129 external code.
print('x value is rounded to', • If the base condition is met then the
round(x)) program gives meaningful output and exits.
print('x value is rounded to', • Otherwise, function does some required
round(y,2)) processing and then calls itself to continue
Output: recursion.
x value is rounded to 18
x value is rounded to 22.81 Example:
def fact(n):
(d) type( ) if n == 0:
• Returns the type of an object for the given return 1
single object. else:
• Example: return n * fact (n-1)
X= 15 print (fact (0))
Y= ‘A’ print (fact (5))
Z = True
print(type(X)) 22. Explain about string operators in python
print(type(Y)) with suitable example.
print(type(Z)) String Operators:
Output: • Python provides the following operators for
<class 'int'>
string operations. These operators are
<class 'str'>
useful to manipulate string.
<class 'bool'>

(e) pow( ) (i) Concatenation (+)


• Returns the computation of a raised to the • Joining of two or more strings is called as
power of b. Concatenation.
• Example: • The plus (+) operator is used to
x=5 concatenate strings in python.
y=2
print(pow(x,y)) Example
Output: >>> "welcome" + "Python"
25
'welcomePython'
21. Explain recursive function with an example.

43
(ii) Append (+ =) • In Python, append() function is used to add
• Adding more strings at the end of an a single element and extend() function is
existing string is known as append. used to add more than one element to an
• The operator += is used to append a new existing list.
string with an existing string. • Syntax:
List.append (element to be added)
List.extend ( [elements to be added])
Example
>>> str1="Welcome to " In extend( ) function, multiple elements should be
>>> str1+="Learn Python" specified within square bracket as arguments of the
>>> print (str1) function.
Welcome to Learn Python
• Example
>>> Mylist=[34, 45, 48]
(iii) Repeating (*)
>>> Mylist.append(90)
• The multiplication operator (*) is used to >>> print(Mylist)
display a string in multiple number of times. [34, 45, 48, 90]

Example • The append( ) function in Python is used to


>>> str1="Welcome " add more elements in a list. But, it includes
>>> print (str1*4) elements at the end of a list.
Welcome Welcome Welcome • The insert( ) function is used to insert an
element at any position of a list.
Welcome
• Syntax:
List.insert (position index, element)
(iv) String slicing • Example:
• Slice is a substring of a main string. MyList=[34,98,47,'Apple', 'Mango',
• A substring can be taken from the original 'Orange', 'Pineapple' ]
string by using [ ] operator and index or print(MyList)
subscript values. Thus, [ ] is also known as [34,98,47,'Apple', 'Mango',
slicing operator. 'Orange', 'Pineapple' ]
• Using slice operator, you have to slice one MyList.insert(3, 'Banana')
print(MyList)
or more substrings from a main string.
[34,98,47, 'Banana', 'Apple',
• General format of slice operation: 'Mango', 'Orange', 'Pineapple' ]
str[start:end]
Example I: slice a single character from a string 24. What is the purpose of range( )? Explain
>>> str1="THIRUKKURAL" with an example.
>>> print (str1[0]) • The range( ) is a function used to generate
T a series of values in Python.
• Using range( ) function, you can create list
with series of values.
Example II : slice a substring from index 0 to 4
• Syntax of range ( ) function:
>>> print (str1[0:5])
range (start value, end value, step
THIRU value)
• The range( ) function has three arguments.
23. What the different ways to insert an element 1. start value – beginning value of
in a list. Explain with suitable example. series. Zero is the default beginning
value.

44
2. end value – upper limit of series. • The function union( ) is also used to join two
Python takes the ending value as sets in python.
upper limit – 1.
3. step value – It is an optional
argument, which is used to generate
different interval of values.
• Example:
for x in range (2, 11, 2):
print(x)
• Output
2
4 • Example 1: Using union operator
6 setA={2,4,6,8}
8 setB={'A', 'B', 'C', 'D'}
10 Uset=setA|setB
print(Uset)
24. What is nested tuple? Explain with an Output:
example. {2, 4, 6, 8, 'A', 'D', 'C', 'B'}
• In Python, a tuple can be defined inside • Example 2: Using union function
another tuple; called Nested tuple. setA={2,4,6,8}
• In a nested tuple, each tuple is considered setB={'A', 'B', 'C', 'D'}
as an element. setU=setA.union(setB)
• The for loop will be useful to access all the print(setU)
elements in a nested tuple. Output:
• Example: {'D', 2, 4, 6, 8, 'B', 'C', 'A'}
Toppers = (("Vinodini", "XII-F", 98.7),
("Soundarya", "XII-H", (ii) Intersection:
97.5), • It includes the common elements in two sets
("Tharani", "XII-F", • The operator & is used to intersect two sets
95.3),
in python.
("Saisri", "XII-G",
93.8)) • The function intersection( ) is also used to
for i in Toppers: intersect two sets in python.
print(i)
• Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)

26. Explain the different set operations


supported by python with suitable example. • Example 1: Using intersection operator
(i) Union: setA={'A', 2, 4, 'D'}
• It includes all elements from two or more setB={'A', 'B', 'C', 'D'}
sets print(setA & setB)
• In python, the operator | is used to union of • Output:
two sets. {'A', 'D'}
• Example 2: Using intersection function

45
setA={'A', 2, 4, 'D'}
setB={'A', 'B', 'C', 'D'}
print(setA.intersection(set_B))
• Output:
{'A', 'D'}

(iii) Difference:
• It includes all elements that are in first set • Example 1: Using symmetric difference
(say set A) but not in the second set (say operator
set B) setA={'A', 2, 4, 'D'}
• The minus (-) operator is used to difference setB={'A', 'B', 'C', 'D'}
set operation in python. print(setA ^ setB)
• The function difference( ) is also used to • Output:
difference operation. {2, 4, 'B', 'C'}
• Example 2: using symmetric difference
function
setA={'A', 2, 4, 'D'}
setB={'A', 'B', 'C', 'D'}
print(setA.symmetric_difference(s
etB))
• Output:
{2, 4, 'B', 'C'}

• Example 1: Using difference operator 27. Explain the different types of data model.
setA={'A', 2, 4, 'D'} Following are the different types of a Data Model
setB={'A', 'B', 'C', 'D'} 1. Hierarchical Model
print(setA - setB) 2. Relational Model
3. Network Database Model
• Output:
4. Entity Relationship Model
{2, 4}
5. Object Model
• Example 2: Using difference function 1. Hierarchical Model
setA={'A', 2, 4, 'D'} • Hierarchical model was developed by IBM
setB={'A', 'B', 'C', 'D'} as Information Management System.
print(setA.diff erence(setB)) • In Hierarchical model, data is represented
• Output: as a simple tree like structure form.
{2, 4} • This model represents a one-to-many
relationship ie parent-child relationship.
(iv) Symmetric difference: • One child can have only one parent but one
• It includes all the elements that are in two parent can have many children.
sets (say sets A and B) but not the one that • This model is mainly used in IBM Main
Frame computers.
are common to two sets.
• The caret (^) operator is used to symmetric 2. Relational Model
difference set operation in python. • The Relational Database model was first
• The function symmetric_difference( ) is proposed by E.F. Codd in 1970. Nowadays,
also used to do the same operation. it is the most widespread data model used
for database applications around the world.

46
• The basic structure of data in relational
model is tables (relations). 28. Explain the different types of relationship
• All the information’s related to a particular mapping.
type is stored in rows of that table. 1. One-to-One Relationship
• Hence tables are also known as relations in 2. One-to-Many Relationship
a relational model. A relation key is an 3. Many-to-One Relationship
attribute which uniquely identifies a 4. Many-to-Many Relationship
particular tuple (row in a relation (table)).
1. One-to-One Relationship:
3. Network Model • In One-to-One Relationship, one entity is
• Network database model is an extended related with only one other entity.
form of hierarchical data model. • One row in a table is linked with only one
• The difference between hierarchical and row in another table and vice versa.
Network data model is: • For example: A student can have only one
o In hierarchical model, a child record exam number
has only one parent node,
o In a Network model, a child may 2. One-to-Many Relationship:
have many parent nodes. It • In One-to-Many relationship, one entity is
represents the data in many to-many related to many other entities.
relationships. • One row in a table A is linked to many rows
o This model is easier and faster to in a table B, but one row in a table B is
access the data. linked to only one row in table A.
• For example: One Department has many
4. Entity Relationship Model. (ER model) staff members.
• In this database model, relationship are
created by dividing the object into entity and 3. Many-to-One Relationship:
its characteristics into attributes. • In Many-to-One Relationship, many entities
• It was developed by Chen in 1976. This can be related with only one in the other
model is useful in developing a conceptual entity.
design for the database. • For example: A number of staff members
• It is very simple and easy to design logical working in one Department.
view of data. The developer can easily • Multiple rows in staff members table is
understand the system by looking at ER related with only one row in Department
model constructed. table.

5. Object Model 4. Many-to-Many Relationship


• Object model stores the data in the form of • A many-to-many relationship occurs when
objects, attributes and methods, classes multiple records in a table are associated
and Inheritance. with multiple records in another table.
• This model handles more complex
applications, such as Geographic 29. Differentiate DBMS and RDBMS.
information System (GIS), scientific DBMS RDBMS
experiments, engineering design and
Database Relational DataBase
manufacturing.
Management System Management System
• It is used in file Management System. It
represents real world objects, attributes and
behaviors. It provides a clear modular Navigational model Relational model (in
structure. ie data by linked tables). ie data in tables
• It is easy to maintain and modify the existing records as row and column
code.

47
• It includes all tuples that are in tables A or in
Exhibit Not Present B. It also eliminates duplicates.
RDBMS uses • Set A Union Set B would be expressed as A
Not performed normalization to reduce ∪B
redundancy
Faster, compared to (4) SET DIFFERENCE ( Symbol : - )
Consumes more time • The result of A – B, is a relation which
DBMS.
used to establish includes all tuples that are in A but not in
Does not use. relationship. Keys are B.
used in RDBMS. • The attribute name of A has to match
Inefficient, with the attribute name in B.
Error prone and Efficient and secure.
insecure. (5) INTERSECTION (symbol : ∩) A ∩ B
• Defines a relation consisting of a set of all
Not supported Supported by RDBMS. tuple that are in both in A and B.
SQL server, Oracle, • However, A and B must be union-
Dbase, FoxPro. compatible.
mysql, MariaDB, SQLite.

30. Explain the different operators in Relational (6) PRODUCT OR CARTESIAN PRODUCT
algebra with suitable examples. (Symbol : X )
• Relational Algebra is divided into various • Cross product is a way of combining two
groups relations.
• Unary Relational Operations • The resulting relation contains, both
1. SELECT ( symbol : σ) relations being combined.
2. PROJECT ( symbol : Π) • A x B means A times B, where the relation
• Relational Algebra Operations from Set A and B have different attributes.
Theory • This type of operation is helpful to merge
3. UNION (∪) columns from two relations.
4. INTERSECTION (∩)
5. DIFFERENCE (−) 31. Explain the characteristics of DBMS.
6. CARTESIAN PRODUCT (X) Data is never directly
1. Data stored in stored into the database.
(1) SELECT (symbol : σ) table Data is stored into
• General form σc ( R ) with a relation R and tables, created inside the
a condition C on the attributes of R. database. DBMS also
• The SELECT operation is used for selecting allows to have
a subset with tuples according to a given relationship between
condition. tables which makes the
• Select filters out all tuples that do not satisfy data more meaningful
C. and connected.
2. Reduced In the modern world hard
(2) PROJECT (symbol : Π) Redundancy drives are very cheap,
• The projection eliminates all attributes of the but earlier when hard
input relation but those mentioned in the drives were too
projection list. expensive, unnecessary
repetition of data in
• The projection method defines a relation
database was a big
that contains a vertical subset of Relation.
problem But DBMS
follows Normalisation
(3) UNION (Symbol :∪)
which divides the data in

48
such a way that • Unique constraint
repetition is minimum. • Primary key constraint
• Default constraint
3.Data Consistency On live data, it is being • Check constraint
continuously updated
and added, maintaining Unique constraint:
the consistency of data • This constraint ensures that no two rows
can become a challenge. have the same value in the specified
But DBMS handles it by columns.
itself. • The unique constraint can be applied only to
4. Support Multiple DBMS allows multiple fields that have also been declared as not
user and Concurrent users to work on null.
Access it(update, insert, delete • Example:
data) at the same time Create table student (admno integer
and still manages to NOT NULL UNIQUE);
maintain the data
consistency. Primary key constraint:
5.Query Language DBMS provides users • The constraint declares a field as a Primary
with a simple query key which helps to uniquely identify a
language, using which record.
data can be easily • The primary key does not allow NULL
fetched, inserted, values and therefore a field declared as
deleted and updated in a primary key must have the NOT NULL
database. constraint.
6. Security The DBMS also takes • Example:
care of the security of Create table student (
data, protecting the data admno integer(4) not null primary
from unauthorized key,
access. In a typical sname char(2) not null,
DBMS, we can create mark1 integer(2), mark2 integer(2));
user accounts with
different access Default constraint:
permissions, using which • The default constraint is used to assign a
we can easily secure our default value for the field.
data by restricting user • When no value is given for the specified
access. field having default constraint, automatically
7. DBMS Supports It allows us to better the default value will be assigned to the
Transactions handle and manage data field.
integrity in real world
applications where multi- Check constraint:
threading is extensively • This constraint helps to set a limit value
used. placed for a field.
• When we define a check constraint on a
32. Write the different types of constraints and single column, it allows only the restricted
their functions. values on that field.
Constraint: • Example:
• Constraint is a condition applicable on a Create table student (
field or set of fields. admno integer(4) not null primary
key,
Types of constraints: sname char(2) not null,

49
mark1 integer(2) (check<=70), • CREATE, ALTER, DROP, TRUNCATE.
mark2 integer(2) (check<=90));
DCL - Data Control Language:
• GRANT, REVOKE
33. Consider the following employee table. TCL – Transactional Control Language:
Write SQL commands for the questions (i) to • COMMIT, ROLL BACK, SAVE POINT
(v).
EMP NAME DESIG PAY ALLO DQL – Data Query Language:
CODE WANCE • SELECT
S1001 Hariharan Supervisor 29000 12000
P1002 Shaji Operator 10000 5500 35. Construct the following SQL statements in
P1003 Prasad Operator 12000 6500 the student table-
C1004 Manjima Clerk 8000 4500 (i) SELECT statement using GROUP BY clause.
M1005 Ratheesh Mechanic 20000 7000 (ii) SELECT statement using ORDER BY clause.
(i) To display the details of all employees in
descending order of pay.
(ii) To display all employees whose allowance is Answer:
between 5000 and 7000. SELECT * FROM Student ORDER BY
(iii) To remove the employees who are mechanic. Name;
(iv) To add a new row. SELECT Gender, count(*) FROM Student
(v) To display the details of all employees who are GROUP BY Gender;
operators.
36. Write a SQL statement to create a table for
Answer:
employee having any five fields and create a
(i) SELECT * from emp ORDER BY pay
DESC; table constraint for the employee table.
(ii) SELECT * from emp WHERE allow CREATE TABLE Employee
BETWEEN 5000.00 and 7000.00; (Empno integer(4) NOT NULL,
(iii) DELETE from emp WHERE EmpName varchar (20) NOT NULL,
desig='Mechanic'; Gender char (1),
(iv) INSERT INTO emp (empcode, ename, Age integer(2),
Desig, Pay, Allow) VALUES (1006, Dept varchar(10),
'Kumar', 'Manager', 30000.00, PRIMARY KEY (Empno));
17000.00);
(v) SELECT * from emp WHERE 37. Differentiate Excel file and CSV file.
desig='Operator'; Excel CSV
Excel is a binary file that CSV format is a plain
34. What are the components of SQL? Write the holds information about text format with a series
commands in each. all the worksheets in a of values separated by
Components of SQL: file, including both commas.
• DML – Data Manipulation Language content and formatting
• DDL – Data Definition Language XLS files can only be CSV can be opened
• DCL – Data Control Language read by applications that with any text editor in
• TCL – Transaction Control Language have been especially Windows like notepad,
• DQL – Data Query Language written to read their MS Excel, OpenOffice,
format, and can only be etc.
DML – Data Manipulation Language: written in the same way.
• INSERT, DELETE, UPDATE. Excel is a spreadsheet CSV is a format for
that saves files into its saving tabular
DDL – Data Definition Language: own proprietary format information into a

50
viz. xls or xlsx delimited text file with with double quotes, then double quotes may
extension .csv not appear inside the fields.
Excel consumes more Importing CSV files can 6. Fields containing line breaks (CRLF),
memory while importing be much faster, and it double quotes, and commas should be
data also consumes less enclosed in double-quotes.
memory 7. If double-quotes are used to enclose fields,
then a double-quote appearing inside a field
38. Write the different methods to read a File in must be preceded with another double
Python. quote.
• You can read the contents of CSV file with
the help of csv.reader() method. 40. Explain each word of the following
• The reader function is designed to take command.
each line of the file and make a list of all Python <filename.py> -<i> <C++ filename
columns. without cpp extension>
• Using this method one can read data from Python The keyword to execute the
csv files of different formats like quotes (" "), Python program from
pipe (|) and comma (,). command line
• The syntax for csv.reader() <filename.py> Name of the Python
sv.reader(fileobject,delimiter,fmtpara program to executed
ms)
Methods to read a file -<i> The input mode
1. CSV file - data with default delimiter comma
(,) <C++ filename The name of C++ file to be
2. CSV file - data with Space at the beginning without cpp compiled and executed
3. CSV file - data with quotes extension>
4. CSV file - data with custom Delimiters

39. Write the rules to be followed to format the 41. What is the purpose of sys, os, getopt
data in a CSV file. module in Python. Explain
1. Each record (row of data) is to be located (i) Python’s sys module:
on a separate line, delimited by a line break • This module provides access to some
by pressing enter key. variables used by the interpreter and to
2. The last record in the file may or may not functions that interact strongly with the
have an ending line break. interpreter.
3. There may be an optional header line • sys.argv is the list of command-line
appearing as the first line of the file with the arguments passed to the Python program.
same format as normal record lines. The Argv contains all the items that come along
header will contain names corresponding to via the command-line input, it's basically an
the fields in the file and should contain the array holding the command-line arguments
same number of fields as the records in the of the program.
rest of the file.
4. Within the header and each record, there (ii) Python's OS Module:
may be one or more fields, separated by • The OS module in Python provides a way of
commas. Spaces are considered part of a using operating system dependent
field and should not be ignored. The last functionality.
field in the record must not be followed by a • The functions that the OS module allows
comma. you to interface with the Windows operating
5. Each field may or may not be enclosed in system where Python is running on.
double quotes. If fields are not enclosed • os.system( ): Execute the C++ compiling
command (a string contains Unix, C

51
command which also supports C++ 43. Write in brief about SQLite and the steps
command) in the shell (Here it is Command used to use it.
Window). • SQLite is a simple relational database
system, which saves its data in regular data
(iii) Python getopt module: files or even in the internal memory of the
• The getopt module of Python helps you to computer.
parse (split) command-line options and • It is designed to be embedded in
arguments. This module provides two applications, instead of using a separate
functions to enable command-line argument database server program such as MySQLor
parsing. Oracle.
• getopt.getopt method: This method parses • SQLite is fast, rigorously tested, and fl
command-line options and parameter list. exible, making it easier to work. Python has
• The syntax: a native library for SQLite.
<opts>,<args>=getopt.getopt(argv, • Steps to use SQLite:
options, [long_options]) Step 1: Import sqlite3
• Step 2: Create a connection using connect()
42. Write the syntax for getopt() and explain its method and pass the name of the database
arguments and return values File
• This method parses command-line options • Passing the name of the database to
and parameter list. be accessed. If the database already
• The syntax: exists the connection will open the
<opts>,<args>=getopt.getopt(argv, same. Otherwise, Python will open a
options, [long_options]) new database file with the specified
name.
o argv − This is the argument list of • Step 3: Set the cursor object cursor =
values to be parsed (splited). In our connection. cursor( )
program the complete command will • A control structure used to traverse
be passed as a list. and fetch the records of the
o options − This is string of option database.
letters that the Python program
recognize as, for input or for output, 44. Write the Python script to display all the
with options (like ‘i’ or ‘o’) that records of the following table using
followed by a colon (:). Here colon is fetchmany( )
used to denote the mode. Icode ItemName Rate
o long_options −This parameter is
passed with a list of strings. 1003 Scanner 10500
Argument of Long options should be 1004 Speaker 3000
followed by an equal sign ('='). 1005 Printer 8000
• getopt() method returns value consisting of 1008 Monitor 15000
two elements. 1010 Mouse 700
• Each of these values are stored separately Answer:
in two different list (arrays) opts and args. import sqlite3
o Opts contains list of splitted strings connection = sqlite3.connect("Spares.db")
like mode, path and args contains cursor = connection.cursor()
any string if at all not splitted cursor.execute("SELECT * FROM
because of wrong path or mode. hardware")
o args will be an empty array if there print("fetching all records:")
is no error in splitting strings by result = cursor.fetchmany(5)
getopt(). print(result)

52
45. What is the use of HAVING clause? Give an cursor = connection.cursor()
example python script cursor.execute("UPDATE suppqty+40
• Having clause is used to filter data based on FROM supplier WHERE name= “Akila”
the group functions. This is similar to result = cursor.fetchall()
WHERE condition but can be used only with print(*result,sep="\n")
group functions.
• Group functions cannot be used in WHERE 47. Explain in detail the types of pyplots using
Clause but can be used in HAVING clause. Matplotlib.
• Example: (i) Line Chart
import sqlite3 • A Line Chart or Line Graph is a type of chart
connection = sqlite3.connect("Academy.db") which displays information as a series of
cursor = connection.cursor() data points called ‘markers’ connected by
cursor.execute("SELECT straight line segments.
GENDER,COUNT(GENDER) FROM • A Line Chart is often used to visualize a
Student GROUP BY GENDER HAVING trend in data over intervals of time – a time
COUNT(GENDER)>3") series – thus the line is often drawn
result = cursor.fetchall() chronologically.
co = [i[0] for i in cursor.description]
print(co) (ii) Bar Chart
print(result) • A BarPlot (or BarChart) is one of the most
common type of plot.
46. Consider the following table Supplier and • It shows the relationship between a
item. Write a python script for (i) to (ii) numerical variable and a categorical
SUPPLIER variable.
Suppno Name City Icode SuppQty • Bar chart represents categorical data with
S001 Prasad Delhi 1008 100 rectangular bars.
S002 Anu Bangalore 1010 200 • Each bar has a height corresponds to the
S003 Shahid Bangalore 1008 175 value it represents. The bars can be plotted
S004 Akila Hydrabad 1005 195 vertically or horizontally.
S005 Girish Hydrabad 1003 25 • It’s useful when we want to compare a given
S006 Shylaja Chennai 1008 180 numeric value on different categories. To
S007 Lavanya Mumbai 1005 325 make a bar chart with Matplotlib, we can
use the plt.bar() function.
(i) Display Name, City and Icode of suppliers who
do not reside in Delhi. (iii) Pie Chart
(ii) Increment the SuppQty of Akila by 40 • Pie Chart is probably one of the most
common type of chart.
Answer: • It is a circular graphic which is divided into
(i) slices to illustrate numerical proportion.
import sqlite3 • The point of a pie chart is to show the
connection = sqlite3.connect("ABC.db") relationship of parts out of a whole.
cursor = connection.cursor() • To make a Pie Chart with Matplotlib, we can
cursor.execute("SELECT name, city, icode use the plt.pie() function.
FROM supplier WHERE NOT (city=“Delhi”) • The autopct parameter allows us to display
result = cursor.fetchall() the percentage value using the Python
print(*result,sep="\n") string formatting.

(ii) 48. Explain the various buttons in a matplotlib


import sqlite3 window.
connection = sqlite3.connect("ABC.db") • Home Button:

53
The Home Button will help once you have • Configure Subplots:
begun navigating your chart. If you ever This button allows you to configure various
want to return back to the original view, you spacing options with your figure and plot.
can click on this.
• Save Figure:
• Forward/Back buttons: This button will allow you to save your figure
These buttons can be used like the Forward in various forms.
and Back buttons in your browser. You can
click these to move back to the previous 49. Explain the purpose of the following
point you were at, or forward again. functions:
a. plt.xlabel
• Pan Axis: Assign labels to x axis
This cross-looking button allows you to click
it, and then click and drag your graph b. plt.ylabel
around. Assign labels to y axis

• Zoom: c. plt.title
The Zoom button lets you click on it, then Assign plot title
click and drag a square that you would like
to zoom into specifically. Zooming in will d. plt.legend()
require a left click and drag. You can Assign default legend
alternatively zoom out with a right click and
drag. e. plt.show()
Used to invoke graph window

******

All the Best

54

You might also like