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

yasi

The document provides an overview of fundamental programming concepts, including definitions of subroutines, interfaces, abstract data types, and various data structures like lists and tuples. It discusses the importance of scope, mapping, sorting, searching, and data visualization, along with the characteristics of algorithms and their complexities. Additionally, it covers Python-specific topics such as functions, operators, and the use of CSV files.

Uploaded by

Mohamed Yasin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

yasi

The document provides an overview of fundamental programming concepts, including definitions of subroutines, interfaces, abstract data types, and various data structures like lists and tuples. It discusses the importance of scope, mapping, sorting, searching, and data visualization, along with the characteristics of algorithms and their complexities. Additionally, it covers Python-specific topics such as functions, operators, and the use of CSV files.

Uploaded by

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

1. What is a subroutine?

 The basic building blocks of computer programs


 Small sections of code that are used to perform a particular task that can be used
repeatedly called as Functions in Programming languages.

2. Differentiate interface and the implementation .


INTERFACE IMPLEMENTATION
Interface just defines In object oriented
what an object can do, programs classes are the
but won't actually do it. interface.
In object oriented In object oriented
programs classes are programs, how the object
the interface. is processed and executed
is the implementation.
I. BOOK
BACK QUESTIONS:
1. What is abstract data type?
 Abstract Data type is a type or class for objects whose behaviour is defined by a set of
value and a set of operations.

2. Differentiate constructors and selectors.


CONSTRUCTORS SELECTORS
Constructors are functions Selectors are functions that
that built the abstract data retrieve information from
type. the data type.

3. What is a Pair? Give an example.


 Any way of handling two values together into one can be considered as a pair. Lists
are a common method to do so. Therefore List can be called as Pairs.
Example for List is [10, 20].
4. What is a List? Give an example.
 List is constructed by placing expressions within square brackets separated by
commas. Such an expression is called a list literal. List can store multiple values.
 Each value can be of any type and can even be another list. Example for List is [10, 20]
5. What is a Tuple? Give an example.
A tuple comma - separated sequence of values surrounded with parentheses.

Example: colour =('red', 'blue', 'Green')


1. What is a scope?
 Scope refers to the visibility of variables,parameters and functions in one part of a
program to another part of the same program.
 In other words, which parts of our program can see or use it.

2. Why scope should be used for variable. State the reason?


 To limit a variable's scope to a single definition scope is needed. In this way, changes
inside the function can't affect the variable on the outside of the function in
unexpected ways.

3. What is Mapping?
 The process of binding a variable name with an object is called mapping.
 = (equal to sign) is used in programming languages to map the variable and object.

1. What is Sorting?
 Arranging the data in ascending or descending order is called sorting.

2. What is searching? Write its types.


 Searching is the process of finding a particular data in a collection of data.
Types:
Linear Search or Sequential Search.
Binary Search.
www.nammakalvi.in

1. Write short notes on Tokens.


Python breaks each logical line into a sequence of elementary lexical components
known as Tokens. The normal token types are
 Identifiers
 Keywords
 Operators
 Delimiters and Literals.

2. What are the different operators that can be used in Python?


 In Python the following operators are used
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Conditional Operator

3. What is a literal? Explain the types of literals?


 Numeric - Numeric Literals consists of digits and are immutable
(unchangeable).
 String - In Python astring literal is a sequence of characters surrounded by
quotes.
 Boolean - A Boolean literal can have any of the two values: True or False.

1. What is function?
 Functions are named blocks of code that are designed to do a specific job.

2. Write the different types of function.


 Types of Python Functions:
 User-defined functions
 Built-in functions
 Lambda Functions
 Recursion Functions
www.nammakalvi.in

5. What is the purpose of Destructor?


 Destructor is also a special method gets executed automatically when an object exit
from the scope.
 It is just opposite to constructor. It removes the memory of the object when it goes
out of scope.
 In Python, ___del___( ) method is used as destructor

1. What is normalization?
 Normalization reduces data redundancy and improve data integrity.

1. Write the difference between table constraint and column constraint?


Column constraint: Column constraint apply only to
individual column.
Table constraint: Table constraint applied to a
group of one or more columns.

What is CSV File?


 A CSV file affect human readable text file where each line has a number of fields,
separated by commas or some other delimiter.

2. Mention the two ways to read a CSV file using Python.


There are two ways to read a CSV
file. Use the csv module's reader
function. Use the DictReader class.

CHAPTER
14 Write the expansion of i) SWIGii) MinGW
 SWIG means Simplified Wrapper Interface Generator. MinGW means Minimalist
GNU for Windows.

2. What is the use of modulus?


 Modular programming is a software design technique to split your code into
separate parts. These parts are called modules.
www.nammakalvi.in

CHAPTER 15
1. Define Data Visualization.
 Data visualization is the graphical representation of information and data.
 The objective of Data visualization is to communicate information visually to users.
 For this, data visualization uses statistical graphics.

2. List the general types of data visualization. General types of Data Visualization.
 Charts
 Tables
 Graphs
 Maps
 Infographics
 Dashboards

3. List the types of Visualizations in Matplotlib.


 Line plot
 Scatter plot
 Histogram
 Box plot
 Bar chart and
 Pie chart
www.nammakalvi.in

3 MARKS
CHAPTER 1
I. BOOK BACK QUESTIONS:
1. Mention the characteristics of Interface.
 The class template specifies the interfaces to enable an object to be created and
operated properly.
 An object's attributes and behaviour is controlled by sending functions to the object.
2. Why strlen is called pure function?
 Pure functions are functions which will give exact result when the same arguments
are passed.
 strlen is ye pure function because the function takes one variable as a
parameter,and access it to find its length.
 This function reads external memory but does not change it, and the value returned
derives from the external memory accessed.

3. What is the side effect of impure function? Give example.


 A function has side effects when it has observable interaction with the outside
world.
 Modifying the variable outside of function causes side effect.
For example
let y:=0 (int)
Inc (int) x
y:=y+x;
return(y)
 In the above example the value of 'y' get changed inside the function definition due
to which the result will change each time.
 The side effect of the inc( ) function is, it is changing the data of the external visible
variable 'y'.

4. Differentiate pure and impure function.


PURE FUNCTION IMPURE FUNCTION
The return value of the pure functions The return value of the impure functions
depends on its arguments passed) Hence, if does not solely depend on its arguments
we call the pure functions with the same passed) Hence, if we call the impure
set of arguments, we will always get the functions with the same set of arguments,
same return values. we might get the different return values For
They do not have any side effects. example, random ( ), Date( )
They do not modify the arguments which They may modify the arguments which are
are passed to them. passed to them.
www.nammakalvi.in

5. What happens if you modify a variable outside the function? Give an example.
 Modifying the variable outside of function causes side effect.
For example
let y:=0 (int)
inc (int) x
y:=y+x;
return(y)
 In the above example the value of 'y' get changed inside the function definition due
to which the result will change each time.
 The side effect of the inc( ) function is, it is changing the data of the external visible
variable 'y'.

II. PTA :
1. Write a function that finds the minimum of its three arguments. (PTA - 4)
let min 3 x y z :=
if x<y then
if x<z then x else z
else
if y<z then y else z

III. GOVERNMENT QUESTIONS:


1. Mention the characteristics of interface. (Sep - 20)
2. Differentiate Pure and Impure. (Mar - 20)

CHAPTER 2
I. BOOK BACK QUESTIONS:
1. Differentiate Concrete data type and abstract datatype.
www.nammakalvi.in

Abstract Data Type Concrete Data Type

ADT only mentions what operations are to In country data representation, a


be performed but not how these operations definition for each function is known
will be implemented
ADT does not specify how data will be Concrete data types or structures
organized in memory and what algorithms are direct implementations of
will be used for implementing the relatively simple concept.
operations.
ADT offer a high level view of a concept
independent of its implementation.
2. Which strategy is used for program designing? Define that Strategy.
'Wishful Thinking' strategy is used for program designing.
Definition:
 Wishful Thinking is the formation of beliefs and making decisions according to what
might be pleasing to imagine instead of by appealing to reality.

3. Identify which of the following are constructors and selectors?


Answers

a) N1 = number( ) - Constructor
b) acceptnum(n1) - Selector
c) displaynum(n1) - Selector
d) eval(a/b) - Selector
e) x, y = makeslope (m), makeslope (n) - Constructor
f) display( ) - Selector

4. What are the different ways to access the elements of a list? Give example.
 List is constructed by placing expressions within square brackets separated by
commas. Example for List is [10, 20].
The elements of a list can be accessed in two ways.
o The first way is via our family method of multiple assignment, which unpacks
a list into its elements and binds each element to a different name.

lst:= [10, 20] x, y:= lst o In the above example x will become
10 and why will become 20. A second method for accessing the
elements in a list is by the element selection operator, also
expressed using square-brackets. Unlike a list literal, a square-
www.nammakalvi.in

brackets expression directly following another expression does not


evaluate to a list value, but instead selects an element from the
value of the preceding expression.

lst[0]
10
lst[1]
20
In both the example mentioned above mathematically we can represent list similar
to a set.

lst[(0, 10), (1, 20)] - where

5. Identify which of the following are List, Tuple and class?


Answers

a) arr [1,2,34] - List


b) arr [1, 2, 34] - Tuple
c) student [rno, name, mark] - Class
d) day = (‘sun’, ‘mon’, ‘tue’, ‘wed’) - Tuple
e) x = [1, 5,6.5, [5, 6], 8.2] - List
f) employee [eno, ename, esal, eaddress] - Class
II. GOVERNMENT QUESTIONS:
1. What is a selector? (Sep - 20)
CHAPTER 3
I. BOOK BACK QUESTIONS:
1. Define Local scope with an example.
Local Scope
 Local scope refers to the variables defined in current function.
 A function will first look up for a variable name in its local scope. Only if it does not
find it there, the outer scopes are checked.
Example,
www.nammakalvi.in

 On execution of the above code the variable a displays the value, 7 because it is
defined and available in the local scope.

2. Define Global scope with an example.


 A variable which is declared outside of all the functions in a program is known as
global variable.
 The global variable can be accessed inside or outside of all the functions in a
program.

Example,
 On execution of the above code the variable which is defined inside the function

disp
lays the value 7 for the function call Disp( ) and then it displays 10, because a is
defined in global scope.

3. Define Enclosed scope with an example.


Enclosed Scope:
 A variable which is declared inside a function which contains another function
definition with in it, the inner function can also access the variable of the outer
function. This scope is called enclosed scope.
 When a compiler or interpreter search for a variable in a program, it first search
Local, and then search Enclosing scopes.
www.nammakalvi.in

 In the above example Disp1( ) is defined with in Disp( ). The variable 'a' defined in
Disp( ) can be even used by Disp1( ) because it is also a member of Disp( )

4. Why access control is required?


 Access control is a security technique that regulates who or what can view or use
resources in a computing environment.
 It is a fundamental concept in security that minimizes risk to the object. In other
words access control is a selective restriction of access to data.
 In object oriented programming languages it is implemented through access
modifiers.
 C++ and Java, control the access to class members by public, private and protected
keywords.
 Python prescribes convention of prefixing the name of the variable or method with
single or double underscore to emulate the behaviour of protected and private
access specifiers.

5. Identify the scope of the variables in the following pseudo code and write itsOutput:
color:= Red
mycolor( ):
b:=Blue
myfavcolor( )
g:=Green
print olor, b, g
myfavcolor( ) print
color, b
mycolor( ) print
color

Scope of the variables:


Variables Scope
color:=Red Global
b:=Blue Enclosed
G:=Breen Local

Output:
Red Blue Green
Red Blue
www.nammakalvi.in

Red

CHAPTER 4 I. BOOK BACK QUESTIONS:


1. List the characteristics of an algorithm.
The characteristics of an algorithm:

 Input
 Output
 Finiteness
 Definiteness
 Effectiveness
 Correctness
 Simplicity
 Unambiguous
 Feasibility
 Portable
 Independent

2. Discuss about Algorithmic complexity and its types.


 Computer resources are limited. Efficiency of an algorithm is defined by the
utilization of time and space complexity.

Time Complexity:

 The Time complexity of an algorithm is given by the number of steps taken by the
algorithm to complete the process.

Space Complexity:

 Space complexity of an algorithm is the amount of memory required to run to its


completion.

Example:

 Suppose A is an algorithm and n is the size of input data, the time and space used by
the algorithm A are the two main factors, which decide the efficiency of A.

Time Factor:
www.nammakalvi.in

 Time is measured by counting the number of key operations like comparisons in the
sorting algorithm.

Space Factor:

 Space is measured by the maximum memory space required by the algorithm.


 The complexity of an algorithm f(n) gives the running time and / or the storage space
required by the algorithm in terms of n as the size of input data.

3. What are the factors that influence time and space complexity.
 The efficiency of an algorithm depends on how efficiently it uses time memory
space.
 They are depending on a number of factors such as:
 Speed of the machine.
 Compiler and other system Software tools.
 Operating System.
 Programming language used.  Volume of data required.

4. Write a note on Asymptotic notation.


Asymptotic Notations

 Asymptotic notations are languages that use meaningful statements about time and
space complexity. The following three asymptotic notations are mostly used to
represent time complexity of algorithms:

i) Big O

 Big O is often used to describe the worst case of an algorithm.

ii) Big 
 Big Omega is the reverse Big O, if Big O is used to describe the upper bound (worst
case) of a asymptotic function, Big Omega is used to describe the lower bound
(bestcase).

iii) Big 
 When an algorithm has a complexity with the lower bound = upper bound, say that
an algorithm has a complexity O ( n log n) and  (n log n), it's actually has the
complexity  (n log n), which means the running time of that algorithm always falls
in n log n in the best-case and worst-case.

5. What do you understand by Dynamic programming?


 Dynamic programming approach is similar to divide and conquer. The given problem
is divided into smaller and yet smaller possible sub-problems.
www.nammakalvi.in

 Dynamic programming is used whenever problems can be divided into similar


subproblems. So that their results can be re-used to complete the process.
 Dynamic programming approaches are used to find the solution in optimized way.
For every inner sub-problem, dynamic algorithm will try to check the results of the
previously solved sub-problems.
 The solution of overlapping sub-problems are combined in order to get the better
solution.

Steps to do Dynamic programming:

 The given problem will be divided into smaller overlapping sub-problems.


 An optimum solution for the given problem can be achieved by using result of
smaller sub-.
 Dynamic algorithm uses Memorization.

II. PTA:
1. Write the pseudo code for linear search. (PTA - 4)

 Traverse the array using for loop


 In every iteration, compare the target search key value with the current value of the
list.
 If the values match, display the current Index and value of the
array.
 If the values do not match, move on to the next array element.
 If no match is found, display the search element not found.

2. What are the different phases of analysis and performance evaluation of an


algorithm? (PTA - 5)
A Priori estimates

 This is a theoretical performance analysis of an algorithm. Efficiency of an algorithm is


measured by assuming the external factors.

A Posteriori Testing

 This is called performance measurement. In this analysis actual statistics like running
time and required for the algorithm.

3. What are the factors that measure the execution time of an algorithm? (PTA - 6)

 Speed of the machine.


 Compiler and other system software tools.
 Operating system.
 Programming language used.  Volume of data required.
www.nammakalvi.in

4. Write a pseudocode for bubble sort algorithm. (PTA - 3)

 Start with the first element, i.e index=0 compare the current element with the next
element of the array
 If the current element is greater than the next element of the array, swap them
 If the current element is less than the next or right side of the element, move to the
next element. Go to step 1 and repeat until end of the index is reached.

III. GOVERNMENT QUESTIONS:


1. Write a note on Asymptotic notation. (Mar - 20)

CHAPTER 5
I. BOOK BACK QUESTIONS:
1. Write short notes on Arithmetic operator with examples.
Arithmetic operators

 An arithmetic operator is a mathematical operator that takes two operands and


performs a calculation on them. They are used for simple arithmetic.
 Python supports the following Arithmetic operators.
www.nammakalvi.in

2. What are the assignment operators that can be used in Python?


Assignment operators:

 In Python,= is a simple assignment operator to assign values to variable. 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 to the variables a
and b respectively.
 Python supports the following Assignment operators.

Operator Description Example


Assume x=10

= Assigns right side operands to >>>x=10


left variable >>>b="Computer"
+= Added and assign back >>>x+=20#x=x+20
the result to left operand
i.e. x=30
-= Subtracted and assign back >>>x-5#x=x+5
the result to left operand i.e.
x=25
www.nammakalvi.in

*= Multiplied and assign back the >>>x*5#x=x*5


result to left operand. i.e.
x=125
/= Divided and assign back the >>>x%=3#x=x%3
result to to left operand i.e.
x=62.5
%= Taken modulus (Reminder) >>>x%=3#x=x%3
using two operands and
assign the result to left
operand i.e. x=25
**= Performed exponential >>>x*2=2 # x=x*2
(power) calculation on
operators and assign value to
the left operand i.e. x=6.25
//= Performed floor division on >>> x//=3
operators and assign value to
the left operand i.e. x=2.0
3. Explain Ternary operator with examples.
 Ternary operator is also known as conditional operator that evaluates something
based on a condition being true or false.
 It simply allows testing a condition in a single line replacing the multiline if-else
making the code compact.
The Syntax conditional operator is,:

Variable Name = [on_true] if [Test expression] else [on_false]

Example:
min = 50 if 49<50 else 70 #Output: min= 50
min = 50 if 49>50 else 70 #Output: min= 70
4. Write short notes on Escape sequences with examples.
 In Python strings, the backslash "\" is a special character, also called the "escape"
character.
 It is used in representing certain whitespace characters: “\t” is a tab, “\n” is a
newline, and “\r” is a carriage return.
 For example to print the message “It’s raining”, the Python command is >>> print
(“It\’s raining”) It’s raining
Python supports the following escape sequence characters.
www.nammakalvi.in

5. What are string literals? Explain.


 In Python a string literal is a sequence of characters surrounded by quotes.
 Python supports single, double and triple quotes for a string.
 A character literal is a single character surrounded by single or double quotes. The
value with triple-quote "' '" is used to give multi-line string literal.
# Example program to test String
Literals : strings = “This is Python” char =
“C”
multiline_str = "'This is a multiline string with more than one line code."' print
(strings) print (char)
print (multiline_str)
#End of the
Program Output:
This is Python
C
This is a multiline string with more than one line code.

II. PTA:
1. What are the rules to be followed while creating an identifier in Python? (PTA - 2)
Identifiers

 An Identifier is a name used to identify a variable, function, class, module or object.

Rules for naming identifiers


 An identifier must start with an alphabet (A).Z or a).z) or underscore (_).
 Identifiers may contain digits (0 .. 9)
 Python identifiers are case sensitive i.e. uppercase and lowercase letters of distinct.
www.nammakalvi.in

 Identifiers must not be a Python keyword.


 Python does not allow punctuation characters such as %,$, @ etc), within identifiers.

Example of valid identifiers


Sum, total__marks, regno, num1
Example of invalid identifiers
12Name, name$, total-mark, continue
III. GOVERNMENT QUESTIONS:
1. Explain Ternary operator with examples. (Mar - 20)

CHAPTER 6 I. BOOK BACK QUESTIONS:


1. Write a program to display.
A
AB
ABC
ABCD
ABCDE
PROGRAM
a=['A','B','C','D','E']
for i in range (0,i):
print (a[j], end = " ")
else:
print( )
www.nammakalvi.in

2. Write note on if..else structure. if..else statement

 The if..else statement provides control to check the true block as


well as the false block.
 The syntax of 'if..else' statement; if<condition>:

statements-block 1
else: statements-
block 2

if..else statements execution


is to be executed.

if.. statement thus provides two possibilities and the condition determines which BLOCK
else

Example:
a= int(input ("Enter any number:"))
if a%2==0: print (a, "is an even

number")

else:
print (a, is an odd number")
www.nammakalvi.in

3. Using if..else..elif statement write a suitable program to display largest of 3 numbers.


num1 = float (input("Enter first number:")) num2 = float (input("Enter second number:"))
num3 = float (input("Enter third number:"))
if (num 1>=num2) and (num-1>=num3):
biggest = num-1
elif (num2>= num-1) and (num2>=num3):
biggest = num2
else:
biggest = num3
print("The biggest number between", num1,","num2,"and,num3,"is",biggest)
Output
= RESTART:C:/Users/Syed/AppData/Local/Programs/Python/
Python37-32/c6PC3.py =
Enter first number: 45
Enter second number : 123
Enter third number : 36
The biggest number between 45.0, 123.0 and 36.0 is 123.0
>>>
4. Write the syntax of while loop.
Syntax:
while<condition>:
statements block 1
[else:
statements block 2]
5. List the differences between break and continue statements.
Break Continue
The break statement Continue statement is
terminates the loop used to skip the
containing it. Control of remaining part of a loop
the program flows to and start with next
the statement iteration.

immediately after the


www.nammakalvi.in

body of the loop.


II. PTA:
1. What is the role of range ( ) in for loop in Python? (PTA - 1)

 range( ) generates a list of values starting from start till stop-1. 


The syntax of range( ) is as follows:

range (start, stop, [step])


Where,

 start - refers to the initial value


 stop - refers to the final value
 step - refers to increment value, this is optional part.

Example:
range (1, 30, 1)will start the range of values from 1 and
end at 29
2. Draw a flowchart to explain while loop. (PTA - 2)

while loop execution

3. Write the syntax of if . . . elif . . else statement in Python.


- 3) (PTA

Syntax
if<condition-1>: statements-
block 1
elif<condition-2>:
statements-block 2
else:
statements-block n
www.nammakalvi.in

III. GOVERNMENT QUESTIONS:


1. Which jump statement is used as placeholder? Why? (MQP - 19)

 Pass statement is generally used as a placeholder. When we have a look or function


that is to be implemented in the future and not now, we can't develop such
functions or loops with empty body segment because the interpreter would raise an
error so to avoid this we can use pass statement to construct a body that does
nothing.

CHAPTER 7
I. BOOK BACK QUESTIONS:
1. Write the rules of local variable.
Local scope

 A variable declared inside the function's body or in the local scope is known as local
variable.

Rules of local variable

 A variable with local scope can be accessed only within the function/ block that it is
created in.
 When a variable is created inside the function/block, the variable becomes local to
it.
 A local variable only exists while the function is executing.  The formate of
arguments are also local to function.

2. Write the basic rules for global keyword in python.


Global scope

 A variable, with global scope can be used anywhere in the program.


 It can be created by defining a variable outside the scope of any function/block.

Rules of global Keyword

 The basic rules for global keyword in Python are:


 When we define a variable outside a function, it's global by default.We don't
have to use global keyword.
 We use global keyword to read and write a global variable inside a function. 
Use of global keyword outside a function has no effect.

3. What happens when we modify global variable inside the function?


 Without using the global keyword we cannot modify the global variable inside the
function but we can only access the global variable.

Modifying Global Variable From Inside the Function


www.nammakalvi.in

c = 1 # global variable
def add( ): c = c+2 #
increment c by 2
print (c)
add( )
Output
Unbound Local Error: local variable 'c' referenced before assignment.
Changing Global variable From Inside a Function using global keyword
x=0 # global variable
def add( ):
global x
x = x+5 # increment by 2 print ("Inside add( )
function x value is:", x) add( )
print ("In main x value is : ", x)
Output
Inside add ( ) function x value is : 5
In main x value is : 5
4. Differentiate ceil( ) and floor( ) function?
ceil ( ) floor ( )
Returns the smallest integer Returns the largest integer
greater than or equal to x less than or equal to x
Syntax : math.ceil (x) Syntax:math.floor(x)
Example: Example:
x= 26.7 x = 26.7
print (math.ceil (x)) print (math.floor (x))

Output: Output:
27 26

5. Write a Python code to check whether a given year is leap year or not.
PROGRAM:
def leap_year(y):
www.nammakalvi.in

if y%400 == 0: print(y,"is a
leap year")
elif y%4 == 0:
print(y," is a leap year")
else:
print(y," is not a leap year")
year=int(input("Enter a year"))
print(leap_year(year))
Output:
Enter a year 2019
2019 is not a leap year
None
>>>
= RESULT : C:/Users/Syed/AppData/Local/Programs/Python/Python37-32/c7pc5.py=
Enter a year 2020
2020 is a leap year
None
>>>
6. What is composition in functions?
 The value returned by a function may be used as an argument for another function
in a nested manner. This is called composition.
 For example, if we wish to take an expression as a input from the user, we take the
input string from the user using the function input( ) and apply eval( ) function to
evaluate its value.

Example Code:
>>> n2 = eval (input ("Enter an arithmetic expression:"))
Enter an arithmetic expression: 12.0+13.0*2
>>>n2
38.0
7. How recursive functions works?
 When a function calls itself is known as recursion.
www.nammakalvi.in

How recursive function works:


 Recursive function is called by some external code.
 If the base condition is met then the program gives meaningful output and exits.
 Otherwise, function does some required processing and then calls itself to continue
recursion.

Example:
def fact(n):
if n==0:
return 1
else:
return n* fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120
8. What are the points to be noted while defining a function?
 When defining functions the following things that need to be noted;
 Function blocks begin with the keyword "def" followed by function name and
parenthesis( ).
 Any input parameters or arguments should be placed within these parentheses
when you define a function.
 The code block always come after a colon (:) and is indented
 The statement "return [expression]" exists a function, optionally passing back an
expression to the caller.
 A "return" with no arguments is the same as return None.

II. GOVERNMENT QUESTIONS:


1. How recursive function works? (Mar - 20)
CHAPTER 8
I. BOOK BACK QUESTIONS:
1. Write a Python program to display the given pattern.
COMPUTER
www.nammakalvi.in

COMPUTE
COMPUT
COMPU
COMP
COM
CO
C
PROGRAM:
str="COMPUTER"
index=len(str)
for i in str: print
(str[:index])
index-=1
OUTPUT:
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C

2. Write a short about the following with suitable example.


a) capitalize( ) b) swapcase( )
a) capitalize( ) function:
 It is used to capitalize the first character of the string.

Example:
>>> city ="chennai"
www.nammakalvi.in

>>> print(city.capitalize( ))
Output
Chennai
b) swapcase( ) function:
 It is change case of every character to its opposite case vice-versa.

Example:
>>>str="tAmilNaDu"
>>>print(str.swapcase())
Output
TaMILnAdu
3. What will be the output of the given Python program?
str1=”welcome”
str2=”to school”
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
Output
weol
4. What is the use of format ( )? Give an example.
 The format( )function used with strings is very versatile and powerful function used
for formatting strings.
 The curly braces { } are used as placeholders or replacement fields which get
replaced along with format( )function.

Example:
num1=int (input("Number 1:")) num2=int (input("Number 2:")) print
("The sum of { } and { } is { }".format(num1,num2,(num1+num2)))
Output

Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88

5. Write a note about count ( ) function in python.


www.nammakalvi.in

 Returns the number of substrings occurs within the given range.


 Substring may be a single character.
 Range (beg and end) arguments are optional. If it is not given, Python searched in
while string.
 Search is case sensitive.

Example:
>>> str1=" Raja Raja Chozhan"
>>> print(str1.count('Raja'))
2
>>> print(str1.count('r'))
0
>>> print(str1.count('R'))
2
>>> print(str1.count('a'))
5
>>> print(str1.count('a',0,5))
2
>>> print(str1.count('a',11))
1
II. PTA
1. What will be the output? (PTA - 4)
Str 1= "welcome"
Str 2="to school"
Str 3= str 1 [:3] + str 2 [len (str2) - 1:]
print(str3)

Output:

2. How index value allocated to each character of a string in Python? (PTA - 5)


Accessing characters in a String

 Once we define a string, python allocate an index value for its each character.
www.nammakalvi.in

 The index values are otherwise called as subscript which are used to access and
manipulate the strings.
 The subscript can be positive or negative integer numbers.
 The positive subscript 0 is assigned to the first character and n-1 to the last
character, where n is the number of characters in the string.
 The negative index assigned from the last character to the first character in reverse
order begins with -1.

Example
String S C H O O L
Positive
0 1 2 3 4 5
subscript
Negative
-6 -5 -4 -3 -2 -1
subscript

3. Write a note on string formatting operators of Python. (PTA - 6)

 The string formatting operator % is used to construct strings, replacing parts of the
strings with the data stored in variables.

Syntax:
(“String to be display with %val1 and %val2” %(val1, val2))

Example: name = “Rajarajan” mark = 98 print


(“Name: %s and Marks: %d” %(name, mark)

Output:
Name : Rajarajan and Marks: 98
Formatting characters:

Form characters USAGE


%c Character
%d Signed decimal integer
%s String
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal integer (lower case x refers a-f; upper case
X refers A-F)
%e or %E Exponential notation
%f Floating point numbers
www.nammakalvi.in

%g or %G Short numbers in floating point or exponential notation


4. Explain about slicing and slicing with stride. (PTA - 6)
Slicing:

 Slice is a substring of a main string. A substring can be taken from the original string
by using [ ] operator and index or subscript values. Thus, [ ] is also known as slicing
operator. Using slice operator, you have to slice one or more substrings from a main
string.

General format of slice operation:


str[start:end]

 Where start is the beginning index and end is the last index value of a character in
the string. Python takes the end value less than one from the actual index specified.
For example, if you want to slice first 4 characters from a string, you have to specify
it as 0 to 5. Because, python consider only the end value as n-1.

Example I: slice a single character


from a string
>>> str1=”THIRUKKURAL”
>>> print (str1[0]
Example II: slice a substring from
index 0 to 4
>>> print (str1[0:5])
THIRU
Stride when slicing string:
 When the slicing operation, you can specify a third argument as the stride, which
refers to the number of characters to move forward after the first character is
retrieved from the string. The default value of stride is 1.

Example
>>> str1 = “Welcome to learn Python”
>>> print (str1[10:16])
learn
www.nammakalvi.in

>>> print (str1[10:16:4])


r
>>> print (str1[10:16:2])

er

>>> print (str1[::3])


Wceoenyo

III. GOVERNMENT QUESTIONS:


1. What is the use of the operator += in Python string operation?
Append (+=)

 Adding more strings at the end of an existing string is known as append. The operator
+= is used to append a new string with an existing string.

Example:
>>> str1 = “Welcome to”
>>> str1+=”Learn Python”

>>> print (str1)

Welcome to Learn Python


(or)
Write a short note on string slicing with syntax and example. (MQP - 19)

CHAPTER 9
I. BOOK BACK QUESTIONS:
1. What are the advantages of Tuples over a list?
Advantages of Tuples over list :
 The elements of a list are changeable (mutable) whereas the elements of a
tuple are unchangeable (immutable), this is the key difference between tuples
and list.
 The elements of a list are enclosed within square brackets. But, the elements of
a tuple are enclosed by paranthesis. Iterating tuples is faster than list.
2. Write a shot note about sort ( ).
www.nammakalvi.in

sort( ) Sorts the element in list Lists.sort(reverse=True[False, key=myFunc)


Both arguments are optional Mylist=["Thilothamma', 'Tharani', Anitha',
1) If reverse is set as True, list sorting is in 'Saisree', 'Lavanya']
descending order. MyList.sort( )
2) Ascending is default. print(MyList)
3)Key = myFunc; "myFunc" - the name of Mylist.sort(reverse=True) print(MyList)
the user defined that specifies the
sorting criteria) Output:
Note : sort( ) will affect the original list. ['Anitha', 'Lavanya', 'Saisree', "Tharani",
"Thilothamma"]
['Thilothamma', 'Tharani', 'Saisree', 'Lavanya',
'Anitha']
3. What will be the output of the following code?
list = [2**x for x in range(5)]
print(list)
Output:
[1, 2, 4, 8, 16]
4. Explain the difference between del and clear ( ) in dictionary with an example.
 In Python dictionary, del keyword is used to delete a particular element.
 The clear( ) function is used to delete all the elements in a dictionary.
 To remove the dictionary, you can use del keyword with dictionary name.

Syntax:
# To delete a particular element.
del dictionary_name[key] # To
delete all the elements
dictionary_name.clear( ) # To
delete an entire dictionary del
dictionary_name
Example:
Dict = {'Roll No' : 12001, 'SName' : 'Meena', 'Mark1': 98, 'Marl2' :
86} print("Dictionary elements before deletion: \n",Dict) del
Dict['Mark1'] # Deleting a particular element print("Dictionary
elements after deletion of a element: \n", Dict) Dict.clear( ) #
www.nammakalvi.in

Deleting all elements print("Dictionary after deletion of all


elements:\n", Dict)
del Dict # Deleting entire dictionary
5. List out the set operations supported by python.
 The Python is supports the following set operations:

(i) Union:
 It includes all elements from two or more sets.

(ii) Intersection:
 It includes the common elements in two sets.

(iii) Difference:
 It includes all elements that are in first set (say set A) but not in the second set (say
set B)

(iv) Symmetric difference:


 It includes all the elements that are in two sets (say sets A and B) but not the one
that are common to two sets.

6. What are the difference between List and Dictionary?


 Difference between List and Dictionary List is an ordered set of elements. But, a
dictionary is a data structure that is used for matching one element (Key) with
another (Value).
 The index values can be used to access a particular element. But, in dictionary key
represents index. The key may be a number of a string.
 List are used to look up a value whereas a dictionary is used to take one value and
look up another value.

II. PTA:
1. Write execution table for the following python code. (PTA - 1) Marks = [10, 20,

30, 40, 50] i=0 sum = 0 while i < 4 :

sum += Marks [i]


i+=1
Execution table
S. No i i<4 Marks Sum i+1
1 0 0<4(T) 10 10 1
2 1 1<4(T) 20 30 2
www.nammakalvi.in

3 2 2<4(T) 30 60 3
4 3 3<4(T) 40 100 4
5 4 4<4(F)

2. What is dictionary? Write its syntax . (PTA - 3)


 In python, a dictionary is a mixed collection of elements.
 The dictionary type stores a key along with its element.
 The keys in a Python dictionary is separated by a colon (:) while the commas work as
a separator for the elements.
 The key value pairs are enclosed with curly braces { }

Syntax of defining a dictionary:


Dictionary_Name = {Key_1:Value_1, Key_2:Value_2, . . . . . Key_n:Value_n}
Example:
# Empty dictionary
Dict 1 = { }
# Dictionary with Key
Dict_Stud = { RollNo: 1234, Name:Murali, Class:XII, Marks:451}
3. Write a simple Python program with list of five marks and print the sum of all
the marks using while loop. (PTA - 5) mark = [ ]
for x in range (0,5):
num = int(input(“Enter Mark:”))
mark+= (num)
print (mark)
c = len(mark)
i=0
sum = 0
while i<c:
sum+= mark[i]
i+=1 print
(“sum”, sum)
III. GOVERNMENT QUESTIONS:
1. What will be the output? (Mar- 20)
www.nammakalvi.in

list = [ 3** x for x in range (5)]


print (list)

CHAPTER 10
I. BOOK BACK QUESTIONS:
1. What are class members? How do you define it?
 Variables defined inside a class are called as "Class Variable" and functions are called
as "Methods".
 Class variable and methods are together known as members of the class.
 The class members should be accessed through objects or instance of class.
 A class can be defined anywhere in a Python program.
 Any class member can be accessed by using object with a dot (.) operator.

Example
class Student:
mark1, mark2, mark3 = 45, 91, 71 #class variable def
process(self): #class method sum = Student.mark1 +
Student.mark2 + Student.mark3 avg = sum/3
print("Total Marks = ", sum) print("Average Marks = ",
avg)
return
S=Student( )
S.process( )

 In the above program, after defining the class, an object S is created.


 The statement S.process ( ), calls the function to get the required output.

2. Write a class with two private class variables and print the sum using a method.
PROGRAM:
www.nammakalvi.in

class Sample:
def_init_(self, n1, n2):
self.__n1=n1
self.__n2=n2
def sum(self):
total = self._n1 + self._n2
print("Class variable 1 = ", self.__
n1) print("Class variable 2 = ",
self.__n2)
print("Sum of class variables = ",total)

S=Sample(12, 14)
S.sum( )
Output
Class variable 1 = 12
Class variable 2 = 14
Sum of class variables = 26
3. Find the error in the following program to get the given output? class Fruits:
def__init__(self, f1, f2):
self.f1=f1
self.f2=f2 def
display(self):
print(“Fruits 1 = %s, Fruit 2 = %s” %(self.f1, self.f2))
F=Fruits(‘Apple’, ‘Mango’) del F.display
F.display( )

Output:
Fruit 1 = Apple, Fruit 2 = Mango
ERROR

 The statement del F.display should be removed to get the required output.

4. What is the output of the following program?


www.nammakalvi.in

Class Greeting: def ___init___(self,


name):
self.___name = name
def display(self):
print(“Good Morning”, self.___name)
obj=Greeting(‘Bindu Madhavan’) obj.display( )
Output:
Good Morning Bindu Madhavan
5. How to define constructor and destructor in Python?
 Constructor is a special function that is automatically executed when an object of a
class is created.
 In Python, there is a special function called "init" which act as a Constructor. It must
begin and end with double underscore. This function will act as an ordinary function;
but only difference is, it is executed automatically when the object is created.
 This constructor function can be defined with or without arguments. This method is
used to initialize the class variables.

General format of_init_method


(Constructor function)
def_init_(self, [args ..........]):
<statements>

Example:
class Sample:
def_init_(self, num):
print("Constructor of class Sample...")
self.num=num
print("The value is :", num)
S=Sample(10)

Output
Constructor of class Sample...
The value is : 10
www.nammakalvi.in

 Destructor is also a special method gets executed automatically when an object exit
from the scope. It is just opposite to constructor.  In Python, _del_( ) method is used
as destructor.

Example
class Sample:
num=0
def_init_(self, var):
Sample.num+=1
self.var=var
print('The object value is =", var)
print("The value of class variable is = ", Sample.num)
def_del_(self):
Sample.num-=1
print("Object with value %d is exit from the scope"%self.var)
S1=Sample(15)
S2=Sample(35)

S3=Sample(45)
del S1
del S1
del S3
Output
The object value is =15
The value of class variable is = 1
The object value is = 35
The value of class variable is= 2
The object value is = 45
The value of class variable is = 3
Object with value 15 is exit from the scope
Object with value 35 is exit from the scope
Object with value for v is exit from the scope
www.nammakalvi.in

II. PTA:
1. What is public and private data member in Python? (PTA - 3)

 The variables which are defined inside the class is public by default. These variables
can be accessed anywhere in the program using the operator.
 A variable prefixed with double underscore becomes private in nature. These
variables can be accessed only within the class.

III. GOVERNMENT QUESTIONS:


1. What is the output ? (MQP - 19) class Greeting:
def_init_(self,name):
self__name= name
def display (self):
print ("Good Morning", self__name)
obj= Greeting ('Tamil Nadu')
obj.display ( )
Output:
Good Morning Tamil Nadu
2. Write a Python program to check and print if the given number is odd or even using class.
(Hy - 19)
3. Write short note on public and private data members in Python. (Sep-20)
CHAPTER 11
I. BOOK BACK QUESTIONS:
1. What is the difference between Select and Project command?
Select command:

 The SELECT operation is used for selecting a subset with tuples according to a given
condition.
 Select filters out all tuples that do not satisfy C.

Example:
STUDENT
Stud No Name Course Year
cs 1 Kannan Big Data II
Gowri
cs 2 R langage I
Shankar
www.nammakalvi.in

cs 3 Lenin Big Data I


cs 4 Padmaja Python I
course = “Big Data” (STUDENT)
Stud No Name Course Year
cs 1 Kannan Big Data II
cs 3 Lenin Big Data I

Project command :

 The projection eliminates all attributes of the input relation but those mentioned in
the projection list.
 The projection method defines a relation that contains a vertical subset of Relation.

Example:

course(STUDENT)
Result
Course
Big Data
R language Python
Programming
2. What is the role of DBA?
Role of database Administrators:

 Database Administrator or DBA is the one who manages the complete database
management system.
 DBA takes care of the security of the DBMS, managing the licence keys, managing
user accounts and access etc.

3. Explain Cartesian Product with a suitable example.


CARTESIAN PRODUCT (Symbol : x)
 Cross product is a way of combining two relations. The resulting relation contains,
both relations being combined.
 A x B means A times B, where the relation A and B have different attributes.
 This type of operation is helpful to merge columns from two relations.

Example:

Cartesian Product
Table A Table B Table A x Table B
www.nammakalvi.in

1
1S S
2
R
1R
3 S

2 R

S
2
Table A = 3
Table B = 2
3
Table A x B = 3 x 2 = 6
R
3
Table A Table B

Stu Nam Stud Subject


d e No
No
cs 1 Kann cs28 Big Data
an
Gowr
i
cs 2 cs62 R langage
Shan
kar
Python
Padm
cs 4 cs25 Programmin
aja
g
Table A Table B

Stu Nam Stud Subject


d e No
No
cs 1 Kann cs28 Big Data
an
cs 1 Kann cs62 R langage
an
Kann Python
cs 1 cs25
an
www.nammakalvi.in

Programming
Gowr
i
cs 2 Cs28 Big Data
Shan
kar
Gowr
i
cs 2 Cs62 R langage
Shan
kar
Gowr Python
i Programming
cs 2 Cs25
Shan
kar
cs 4 Padm Cs28 Big Data
aja
cs 4 Padm cs62 R langage
aja
Padm Python
cs 4 cs25
aja Programming
4. Explain Object Model with example.
 Object model stores the data in the form of objects, attributes and methods, classes
and Inheritance.
 This model handles more complex applications, such as Geographic information
System (GIS), scientific experiments, engineering design and manufacturing.
 It is used in file Management structure. It represents real world objects, attributes
and behaviors.
 It provides a clear modular structure. It is easy to maintain and modify the existing
code.

Object Model

Shape
get_area( )
get_perimeter( )

Circle Rectangle Triangle


Radius Length Base
breadth Height

 An example of the Object model is Shape, Circle, Rectangle and Triangle are all
objects in this model.
 Circle has the attribute radius.
www.nammakalvi.in

 Rectangle has the attributes length and breadth Triangle has the
attributes base and height.
 The object Circle, Rectangle and Triangle inherit from the object Shape.

5. Write a note on different types of DBMS users.


Types of DBMS Users
Database Administrators
 Database Administrator or DBA is the one who manages the complete database
management system.
 DBA takes care of the security of the DBMS, managing the licence keys, managing
user accounts and access etc.

Application Programmers or Software Developers


 This user group is involved in developing and designing the parts of DBMS.

End User
 All modern applications, web or mobile, store user data.
 Applications are programmed in such a way that they collect user data and store the
data on DBMS systems running on their server.
 End users are the one who store, retrieve, update and delete data.

Database designers
 They are responsible for identifying the data to be stored in the database for
choosing appropriate structures to represent and store the data.

II. PTA :
1. Write a short note on Unary Relational Operations of DBMS. (PTA - 4)
III. GOVERNMENT QUESTIONS:
1. Write a note on different types of DBMS users. (Sep - 20)
www.nammakalvi.in

CHAPTER 12
I. BOOK BACK QUESTIONS:
1. What is a constraint? Write short note on Primary key constraint.
Constraint:
 Constraint is a condition applicable of a field or set of fields.
 Constraints ensure database integrity.
Primary Key Constraint:
 This constraint declares a field as a Primary key which helps to uniquely identify a
record.
 The primary key does not allow NULL values and therefore a field declared as
primary key must have the NOT NULL constraint.

2. Write a SQL statement to modify the student table structure by adding a new field.
 To add a new column "Address" of type 'char' to the Student table, the command is
used as

Syntax
ALTER TABLE student ADD Address char;
3. Write any three DDL commands.
 SQL commands which comes under Data Definition Language are:

CREATE TABLE COMMAND


 We can create a table by using the CREATE TABLE command. When a table is
created, its columns are named, data types and sizes are to be specified. Each table
must have at least one column.

ALTER COMMAND
 The ALTER command is used to alter the table structure like adding a column,
renaming the existing column, change the data type of any column or size of the
column or delete the column from the table.

TRUNCATE COMMAND
 The TRUNCATE command is used to delete all the rows from the table, the structure
remains and the space is freed from the table.

4. Write the use of Savepoint command with an example.


SAVEPOINT COMMAND
www.nammakalvi.in

 The SAVEPOINT command is used to temporarily save a transaction so that we can


rollback to the point whenever required. The different states of our table can be
saved at anytime using different names and the rollback to that state can be done
using the ROLLBACK command.

SAVEPOINT savepoint_name;
5. Write a SQL statement using DISTINCT keyword.
DISTINCT Keyword
 The DISTINCT keyword is used along with the SELECT command to eliminate
duplicate rows in the table. This helps to eliminate redundant data.

II. PTA:
1. Compare Delete , Truncate and Drop in SQL. (or)
What is the use of DELETE, TRUNCATE and DROP comments in SQL? [PRA - 1,3]
DELETE The DELETE command deletes only the rows from the
table based on the condition given in the where clause
or deletes all the rows from the table if no condition is
specified. But it does not free the space containing the
table.
TRUNCATE The TRUNCATE command is used to delete all the
rows, the structure remains in the table and free the
space containing the table.
DROP The DROP command is used to remove an object from
the database. If we drop a table, all the rows in the
table deleted and the table structure is removed from
the database. Once a table is dropped we cannot get it
back.
III. GOVERNMENT QUESTIONS:
1. Write short note on Delete, truncate, drop in SQL. (Sep - 20)
2. Write short notes on TCL commands. (Mar - 20)

CHAPTER 13
I. BOOK BACK QUESTIONS:
1. Write a note on open ( ) function of python. What is the difference between the two
methods?
Methods:
www.nammakalvi.in

 Open file in current directory and f is file object

f = open ("sample.txt")
 Open file by specifying full path and f is file object

f =open('c:\\pyprg\\ch13sample5.csv')
 The default is reading in text mode. In this mode, while reading from the file the
data would be in the format of strings.
 On the other hand, binary mode returns bytes and this is the mode to be used when
dealing with non-text files like image or exe files.

2. Write a Python program to modify an existing file.


Consider the "student.csv" file contains the following data:
Roll No Name City
1 Harshini, Chennai
2 Adhith, Mumbai
3 Dhuruv, Bengaluru
4 Egiste, Tiruchy
5 Venkat, Madurai
 The following program modify the "student.csv" file by modifying the value of an
existing row in student.csv import csv row = [‘3’, ‘Meena’,’Bangalore’] with
open(‘student.csv’,’r’) asread File:

reader = csv.reader(readFile) lines = list(reader) # list( ) – to


store each row of data as a list lines[3] = row with
open(‘student.csv’, ‘w’) as writeFile:
# returns the writer object which converts the user data with delimiter
writer = csv.writer(writeFile)
#writerows( )method writes multiple rows to a csv
file writer.writerrows(lines) readFile.close( )
writeFile.close( )
3. Write a Python program to read a CSV file with default delimiter comma (,).
#importing csv
import csv
#opening the csv file which is in different location with read mode
with open(‘c:\\pyprog\\sample1.csv’, ‘r’|) asF:
www.nammakalvi.in

#other way to open the file is f= (‘c:\\pyprg\\sample1.csv’,


‘r’) reader = csv.reader(F)
# printing each line of the Data row by
row print(row) F.close( ) Output:
[‘SNO’, ‘NAME’, ‘CITY’]
[‘12101’, ‘RAM’, ‘CHENNAI’]
[‘12102’, ‘LAVANYA’, ‘TIRUCHY’]
[‘12103’, ‘LAKSHMAN’, ‘MADURAI’]
4. What is the difference between the write mode and append mode.
Mode Description
Open a file for writing. Create a new file if it
'w' does not exist or truncates the file if it
exists.
'a' Open for appending at the end of the file
without truncating it. Creates a new file if
it does not exist.
5. What is the difference between reader ( ) and DictReader ( ) function?
 There are two ways to read a CSV file.
 Use the csv module's reader function
 Use the DictReader class

CSV Module's Reader Function:


 We can read the contents of CSV file with the help of csv.reader( )method. The
reader function is designed to take each line of the file and make a list of all columns.
Then, we just choose the column we want the variable data for.
 Using this method one can read data from csv files of different formats like quotes
(""), pipe(I) and comma (,).

The syntax for csv.reader( ) is:


csv.reader(fileobject,delimiter,fmtparams)
where

 file object : passes the path and the mode of the file.
 Delimiter : an optional parameter containing the standard dilects like, I etc
can be omitted.
 Fmtparams : optional parameter which help to override the default values of
the dialects like skipinitialspace, quoting etc. can be omitted. Reading CSV File Into
A Dictionary:
www.nammakalvi.in

 To read a CSV file into a dictionary can be done by using DictReader class of csv
module which works similar to the reader( ) class but creates an object which maps
data to a dictionary. The keys are given by the fieldnames as parameter.
 DictReader works by reading the first line of the CSV and using each comma
separated value in this line as a dictionary key. The columns in each subsequent row
then behave like dictionary values and can be accessed with the appropriate key.

Example:
Reading "sample8.csv" file into a dictionary import
csv filename = 'c:\\pyprg\\sample8.csv'
input_file =
csv.DictReader(open(filename,'r')) for row in
input_file:
print(dict(row)) #dict( ) to print data
Output
{ItemName' 'Keyboard', 'Quantity', : '48'}
{ItemName' 'Monitor', 'Quantity', : '52'}
{ItemName' 'Mouse', 'Quantity', : '20'}
In the above program, DictReader( ) is used to read "sample8. csv"file and map into
a dictionary. Then, the function dict( ) is used to print the data in dictionary format
without order.

II. PTA:
1. How csv.write ( ) function is used to create a normal CSV file in Python? (PTA - 4)
III. GOVERNMENT QUESTIONS:
1. Differentiate reader ( ) and Dict Reader( ). (Mar - 20)
CHAPTER 14
I. BOOK BACK QUESTIONS:
1. Differentiate PYTHON and C++.
S. NO PYTHON C++
Python is typically an "interpreted" C++ is typically "compiled"
1
language. language.
C++ is compiled statically typed
2 Python is a dynamic-typed language.
language.
3 Data type is not required while Data type is required while
www.nammakalvi.in

declaring variable. declaring variable.


It can act both as scripting and It is a general purpose language.
4
general purpose language.
2. What are the applications of scripting language?
Applications of Scripting Languages :
 To automate certain tasks in a program.
 Extracting information from a data set.
 Less code intensive as compared to traditional programming language.
 They can bring new functions to applications and glues complex systems together.
3. What is MinGW? What is its use?
 MinGW refers to a set of runtime header files.
 Used in compiling and linking the code of C, C++ and FORTRAN to be run on
Windows Operating System.

4. Identify the module, operator, definition name for the following.Welcome.display( )


welcome.display( )

5. What is sys.argv? What does it contain?


 sys.argv is there list of command-line arguments passed to the Python program.
 argv contains all the items that come along via the command-line input, it's basically
an array holding the command-line arguments of the program.
main(sys.argv[1]) Accepts the program file (Python program) and the
input file (C++ file) as a list (array). argv[0] contains the
Python program which is need not to be passed
because by default_ main_ contains source code
reference and argv[1]contains the name of the C++ file
which is to be processed.
II. GOVERNMENT QUESTIONS:
1. What are the applications of scripting language. (Sep - 20)
CHAPTER 15
I. BOOK BACK QUESTIONS:
1. What is SQLite? What is it advantage?
www.nammakalvi.in

 SQLite is a simple relational database system, which saves its data in regular data fi
les or even in the internal memory of the computer.

Advantages:
 It is designed to be embedded in applications, instead of using a separate database
server program such as MySQL or Oracle.
 SQLite is fast, rigorously tested, and flexible, making it easier to work.

2. Mention the difference between fetchone( ) and fetchmany ( ).


 The fetchone( ) method returns the next row of a query result set or None in case
there is no row left.
 Displaying specified number of records is done by using fetchmany( ). This method
returns the next number of rows (n) of the result set.

3. What is the use of Where Clause. Give a python statement using the where clause?
SQL WHERE CLAUSE
 The WHERE clause is used to extract only those records that fulfill a specified
condition.
Example:
 To display the different grades scored by male students from "student table":

PYTHON CODE:
import sqlite3
connection = sqlite3.connect("Academy.db")
cursor = connection.cursor( )
cursor.execute("SELECT DISTINCT (Grade) FROM student where gender=
'M"") result = cursor.fetchall( ) print(*result,sep="\n")

Output
('B',)
('A',)
('C',)
('D',)
www.nammakalvi.in

4. Read the following details. Based on that write a python script to display department
wise records.
database name:-organization.db
Table name :- Employee
Columns in the table:- Eno, EmpName, Esal, Dept
PYTHON SCRIPT
import sqlite3 connection =
sqlite3.connect("organization.db") cursor =
connection.cursor( )
Employee_data = [("1001","Raja","10500","sales"),
[("1002","Surya","9000","purchase"),
[("1003","Peter","8000","production"),
[("1004","Mohamed","15000","production"),
[("1005","Mishra","7000","purchase"),
[("1006","Kumar","10000","sales")]-
cursor.execute("""drop table
Employee;""") sql_command = """CREATE
TABLE
Emoyee(Eno INTEGER PRIMARY KEY,
EmpName VARCHAR(20), Esal Integer, Dept
VARCHAR(20));""" cursor.execute(sql_command) for p in
Employee_data:
format_str = """INSERT INTO Employee (Eno, EmpName, Esal, Dept)
VALUES ("{id}","{name}", "{sa}", "{dt}",""" sql_command =
format_str.format(id=p[0], name=p[1] , sa=p[2],dt=p[3])
cursor.execute(sql_command) connection.commit()
cursor.execute("SELECT *FROM Employee ORDER BY Dept")
print("Employee Details Department-wise :")
result = cursor.fetchall()
print(*result,sep="\n")
connection.close( )
www.nammakalvi.in

Output
Employee Details Department -wise:
(1003, 'Peter', 8000, 'production')
(1004,’Mohamed’,15000,’production’)
(1002,’Surya’,9000,’purchase’)
(1005,’Mishra’,7000,’purchase’)
(1001,’Raja’,10500,’sales’)
(1006,’Kumar’,10000,’sales’)

5. Read the following details. Based on that write a python script to display records in
descending order of Eno.
database name : - organization.db
Table name :- Employee
Columns in the table : - Eno, EmpName, Esal,
Dept
PYTHON SCRIPT: import sqlite3 connection =
sqlite3.connect("organization.db") cursor =
connection.cursor( )
Employee_ data = [("1001","Raja","10500"",sales"),
("1002","Surya","9000"",purchase"),
("1003","Peter","8000"",production"),
("1004","Mohamed","15000"",production"),
("1005","Mishra","7000"",purchase"),
("1006","Kumar","10000"",sales")],
cursor.execute"""drop table
Employee;""") sql_command = """CREATE
TABLE
Employee (Eno INTEGER PRIMARY KEY, EmpName VARCHAR(20), Esal Integer,
Dept VARCHAR(20));""" cursor.execute(sql_command) for p in Employee_data:
format_str = """INSERT INTO Employee (Eno, EmpName, Esal, Dept)
VALUES ("{id}","{name}", "{sa}","{dt}",""" sql_command =
www.nammakalvi.in

format_str.format(id=p[0], name=p[1] , sa=p[2],dt=p[3])


cursor.execute(sql_command) connection.commit()
cursor.execute("SELECT *FROM Employee ORDER BY Eno desc")
print("Employee Details number-wise Descending order :")
result = cursor.fetchall()
print(*result,sep="\n")
connection.close( ) Output

Employee Details Employee number-wise Decending order:


(1006,’Kumar’,10000,’sales’)
(1005,’Mishra’,7000,’purchase’)
(1004,’Mohamed’,15000,’production’)
(1003,’Peter’,8000,’production’)
(1002,’Surya’,9000,’purchase’)
(1001,’Raja’,10500,’sales’)

II. GOVERNMENT QUESTIONS:


1. Write a short note on (MQP - 19)
a) fetchall ( ) b) fetchone ( ) c) fetchmany ( )

CHAPTER 16
I. BOOK BACK QUESTIONS:
1. Draw the output for the following data visualization plot.
import matplotlib.pyplot as plt
www.nammakalvi.in

plt.bar([1,3,5,7,9],[5,2,7,8,2], label=”Example one”)


plt.bar([2,4,6,8,20],[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( )

2. Write any three uses of data visualization.


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

3. Write the coding for the following:


a) To check of PIP is Installed in your PC. Check if pip is Installed
 To check if pip is already installed in our system, navigate your command line
to the location of Python’s script directory.
 We can install the latest version of pip from your command prompt using the
following command.

Python-m pip install – U pip


b) To check the version of PIP installed in your PC.
To Check pip version:
 To check the version of pip in our system, type the following command:
 C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Script >
pip – version
 The output in command prompt will look like this:
c) To list the packages in matplotlib.
List Packages
 To view the list of installed packages on our system, use the List command:
 C:\Users\YourName\AppData\Local\Programs\Python\Python36-
32\Scripts>pip list
 The screen will display the list of all the packages installed on our system.

4. Write the plot for the following pie chart output.


www.nammakalvi.in

PYTHON CODE TO PLOT PIE CHART


import matplotlib.pyplot as plt sizes = [29.2, 8.3, 8.3,
54.2] labels =
[“Sleeping”,”Eating”,”Working”,”Playing”] plt.pie
(sizes, labels = labels, labels, autopct = “%.2f”)
plt.axes( ).set_aspect (“equal”) plt.title(“Interesting
Graph \nCheck it out”)
plt.show( )
II. PTA:
1. What is pie chart ? How will you create pie chart in Python? Give an example.
(PTA - 3)
III. GOVERNMENT QUESTIONS:
1. Write a python code to display the following chart. (MQP - 19)

You might also like